diff --git a/cleantalk.php b/cleantalk.php index cff5a0f42..71219dea9 100644 --- a/cleantalk.php +++ b/cleantalk.php @@ -4,7 +4,7 @@ Plugin Name: Anti-Spam by CleanTalk Plugin URI: https://cleantalk.org Description: Max power, all-in-one, no Captcha, premium anti-spam plugin. No comment spam, no registration spam, no contact spam, protects any WordPress forms. - Version: 6.87 + Version: 6.88 Author: CleanTalk - Anti-Spam Protection Author URI: https://cleantalk.org Text Domain: cleantalk-spam-protect @@ -15,6 +15,7 @@ use Cleantalk\Antispam\ProtectByShortcode; use Cleantalk\ApbctWP\Activator; use Cleantalk\ApbctWP\AdminNotices; +use Cleantalk\ApbctWP\BotDetectorService; use Cleantalk\ApbctWP\Constant; use Cleantalk\ApbctWP\ContactsEncoder\ContactsEncoder; use Cleantalk\ApbctWP\Antispam\ForceProtection; @@ -152,7 +153,7 @@ } if ( ! defined('APBCT_BOT_DETECTOR_SCRIPT_URL') ) { - define('APBCT_BOT_DETECTOR_SCRIPT_URL', 'https://fd.cleantalk.org/ct-bot-detector-wrapper.js'); + define('APBCT_BOT_DETECTOR_SCRIPT_URL', BotDetectorService::getWrapperUrl()); } /** @@ -1879,6 +1880,8 @@ function apbct_sfw_update__end_of_update($is_first_updating = false) // Delete update errors $apbct->errorDelete('sfw_update', true); + // Delete outdated errors + $apbct->errorDelete('sfw_outdated', true); // Running sfw update once again in 12 min if entries is < 4000 if ( $is_first_updating && @@ -2349,35 +2352,6 @@ function apbct_rc__uninstall_plugin__check_deactivate() $apbct->plugin_deactivated = true; } -/** - * @param $source - * - * @return bool - */ -function apbct_rc__update_settings($source) -{ - global $apbct; - - foreach ( $apbct->default_settings as $setting => $def_value ) { - if ( array_key_exists($setting, $source) ) { - if ($setting === 'apikey') { - continue; - } - $var = $source[$setting]; - $type = gettype($def_value); - settype($var, $type); - if ( $type === 'string' ) { - $var = preg_replace(array('/=/', '/`/'), '', $var); - } - $apbct->settings[$setting] = $var; - } - } - - $apbct->save('settings'); - - return true; -} - /** * @param string $key * @param string $plugin @@ -2390,7 +2364,7 @@ function apbct_rc__insert_auth_key($key, $plugin) require_once(ABSPATH . '/wp-admin/includes/plugin.php'); if ( is_plugin_active($plugin) ) { - $key = trim($key); + $key = trim($key, " \n\r\t\v\x00"); if ( $key && preg_match('/^[a-z\d]{3,30}$/', $key) ) { $result = API::methodNoticePaidTill( @@ -2656,7 +2630,7 @@ function apbct_cookie() // Cookie names to validate $cookie_test_value = array( 'cookies_names' => array(), - 'check_value' => $apbct->api_key . $apbct->data['salt'], + 'check_value' => $apbct->api_key . $apbct->data['salt'] . '_apbct_cookies_test', ); // We need to skip the domain attribute for prevent including the dot to the cookie's domain on the client. @@ -2751,7 +2725,7 @@ function apbct_cookies_test() return 0; } - $check_string = $apbct->api_key . $apbct->data['salt']; + $check_string = $apbct->api_key . $apbct->data['salt'] . '_apbct_cookies_test'; // generate value $cookie_names = TT::getArrayValueAsArray($cookie_test, 'cookies_names'); foreach ( $cookie_names as $cookie_name ) { @@ -3197,6 +3171,11 @@ function apbctGetContactsEncoder() $contacts_encoder_params->obfuscation_text = $apbct->settings['data__email_decoder_obfuscation_custom_text']; $contacts_encoder_params->do_encode_emails = (int)$apbct->settings['data__email_decoder_encode_email_addresses']; $contacts_encoder_params->do_encode_phones = (int)$apbct->settings['data__email_decoder_encode_phone_numbers']; + $contacts_encoder_params->excluded_strings = \Cleantalk\Common\ContactsEncoder\Exclusions\ExclusionsService::parseExcludedStrings( + isset($apbct->settings['data__email_decoder_excluded_strings']) + ? $apbct->settings['data__email_decoder_excluded_strings'] + : '' + ); return ContactsEncoder::getInstance($contacts_encoder_params); } diff --git a/composer.json b/composer.json index 81a5a667d..368326ed9 100644 --- a/composer.json +++ b/composer.json @@ -16,11 +16,18 @@ "yoast/phpunit-polyfills": "^1.0", "ext-dom": "*", "wp-cli/wp-cli-bundle": "*", - "mockery/mockery": "*", "cleantalk/apbct-installer": "*", - "cleantalk/contacts-encoder": "2.0.18.7", + "cleantalk/contacts-encoder": "^2.2.0", "cleantalk/rate-limiter": "*" }, + "replace": { + "cleantalk/antispam": "*", + "cleantalk/helper": "*", + "cleantalk/http": "*", + "cleantalk/variables": "*", + "cleantalk/cleaner": "*", + "cleantalk/mloader": "*" + }, "scripts": { "test": [ "vendor/bin/phpunit --configuration tests/phpunit.xml --coverage-clover=coverage.xml", diff --git a/css/cleantalk-admin-settings-page.min.css b/css/cleantalk-admin-settings-page.min.css index eaa208fd8..dbba03e03 100644 --- a/css/cleantalk-admin-settings-page.min.css +++ b/css/cleantalk-admin-settings-page.min.css @@ -1 +1 @@ -.apbct_settings-page{padding-right:10px}.apbct_settings-field_content,.cleantalk_link-auto,.cleantalk_link-manual,.ct-warning-test-failed,.ct_rate_block,.ct_settings_banner,i.animate-spin{display:inline-block}#apbctTopWarning{margin-bottom:5px}#apbctTopWarning h3{margin:10px 0 5px 0}#apbctTopWarning h4{margin:10px}#apbctTopWarning h4 span{margin-top:5px}.apbct_settings-subtitle{position:relative;top:-15px;margin:0}.apbct_settings-field_wrapper{margin:15px 0}.apbct_settings-field_wrapper--sub{margin-left:30px!important}.apbct_settings__label{margin-right:10px;font-size:17px;vertical-align:text-bottom}.apbct_settings-field_content{display:inline-block}.apbct_settings-field_content--radio,.apbct_settings-field_wrapper>.apbct_settings-field_description{width:70%;padding-bottom:10px}.apbct_settings-field_title--select,.apbct_settings-field_title--textarea{margin:0;width:210px;padding-right:10px;padding-bottom:10px;font-size:14px;vertical-align:top}.apbct_settings-field_title--radio{display:inline-block;margin:0;width:210px;padding-right:10px;font-size:14px;vertical-align:top}.apbct_input_text{min-width:255px;width:400px}.apbct_settings-long_description---show:hover{color:#aaa;cursor:pointer}.apbct_setting_textarea{min-width:300px}.cleantalk_link{text-decoration:none;font-size:13px;line-height:26px;margin:10px 0 0 0;padding:0 10px 1px;cursor:pointer;border-width:1px;border-style:solid;-webkit-appearance:none;white-space:nowrap;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.cleantalk_link-auto{background:#ccc;border-color:#999;-webkit-box-shadow:inset 0 1px 0 rgba(200,200,200,.5),0 1px 0 rgba(0,0,0,.15);box-shadow:inset 0 1px 0 rgba(200,200,200,.5),0 1px 0 rgba(0,0,0,.15);color:#000;display:inline-block;height:28px;-webkit-border-radius:2px;border-radius:2px}.cleantalk_link-auto:hover{color:#fff}.cleantalk_link-auto.cleantalk_link_text_center{text-align:center}.cleantalk_link-manual{background:#2ea2cc;border-color:#0074a2;-webkit-box-shadow:inset 0 1px 0 rgba(120,200,230,.5),0 1px 0 rgba(0,0,0,.15);box-shadow:inset 0 1px 0 rgba(120,200,230,.5),0 1px 0 rgba(0,0,0,.15);color:#fff;display:inline-block;-webkit-border-radius:3px;border-radius:3px;text-align:center}.cleantalk_link-manual:hover{color:#000}.cleantalk_link[disabled=disabled]{background:#5d9db5;color:#000}.apbct_status_icon{vertical-align:text-bottom;margin:0 5px 0 8px}.apbct-icon-upload-cloud{margin-left:3px}a.ct_support_link{color:#666;margin-right:.5em;font-size:10pt;font-weight:400}.ct-warning-test-failed{display:inline-block;position:relative;padding:5px;margin:4px;border:3px solid #f03232;border-radius:5px;background-color:#ffc8c8}.ct_settings_banner{text-align:right;display:inline-block;width:100%;margin:1em 0;vertical-align:top}#ct_translate_plugin{margin-left:0}.ct_rate_block{display:inline-block;width:370px;margin-right:3em;padding:.8em .8em 15px .8em;text-align:center;border:1px dashed #666}#ct_translate_plugin .apbct_button_rate{margin-bottom:10px}.apbct_long_desc{position:absolute;background:#5a5a5a;min-width:80px;min-height:80px;max-width:500px;padding:10px;color:#fff;z-index:10}.apbct_long_desc a{color:#78c8e6}i.animate-spin{-moz-animation:spin 2s infinite linear;-o-animation:spin 2s infinite linear;-webkit-animation:spin 2s infinite linear;animation:spin 2s infinite linear;display:inline-block;margin:0 auto;font-size:25px;line-height:20px;color:#78c8e6;margin:25px}@keyframes spin{to{transform:rotate(359deg)}}.apbct_long_desc__cancel{position:absolute;top:5px;right:5px;color:rgba(255,255,255,.5)}.apbct_long_desc__cancel:hover{color:#fff}.apbct_long_desc__angle{position:absolute;top:5px;left:-17px;width:10px;height:10px;background:#5a5a5a;-webkit-transform:rotate(135deg);-ms-transform:rotate(135deg);transform:rotate(135deg);-webkit-transform-origin:100% 100%;-ms-transform-origin:100% 100%;transform-origin:100% 100%}.apbct_long_desc__title{color:#78c8e6;margin:0}.--hide{display:none}.apbct_preloader_button{height:15px;margin-left:5px;vertical-align:text-top;display:none}.--invisible{visibility:hidden}.apbct_preloader{height:1em;width:1em;margin-left:.5em;display:inline-block}.key_changed_sync{font-size:1.5em;line-height:2em;vertical-align:middle}.key_changed_success{font-size:1.5em;line-height:2em;vertical-align:middle}.--upper-case{text-transform:uppercase}#cleantalk-modal-content{text-align:center}#cleantalk-modal-content>*{display:block;width:100%}.cleantalk-confirm-modal_header{font-size:15px;font-weight:500}.cleantalk-confirm-modal_text-block{padding:10px 0}.cleantalk-confirm-modal_buttons-block{display:flex!important;gap:10px;justify-content:center}button.ct_support_link{border:none;background:0 0;color:#666;text-decoration:underline;cursor:pointer}.apbct-btn-as-link{padding:0;margin:0;vertical-align:baseline;color:gray;border:0 none;border-bottom:1px solid;cursor:pointer}#apbct-account-email[contenteditable=true]{padding:6px;background-color:#fff;border:1px solid #ccc}button[value=save_changes]:disabled{color:#2271b1;border-color:#2271b1;background:#f6f7f7}#apbct_settings__advanced_settings{position:relative}#apbct_settings__advanced_settings_inner{width:70%}#apbct_hidden_section_nav{position:absolute;top:0;right:0;width:200px}#apbct_hidden_section_nav ul{z-index:9999;width:100%;top:40px}.apbct_settings__position_main_save_button{text-align:right;margin-right:40px}#apbct_settings__after_advanced_settings{margin-bottom:20px;width:70%}#apbct_settings__button_section{position:static;z-index:9999;padding-bottom:40px;bottom:0}.apbct_highlighted{outline-offset:5px;outline-color:red;outline-width:3px!important;outline-style:solid!important}.apbct_notice_inner{display:flex;margin-top:10px!important}.apbct_notification__advanced_settings{margin:20px 0;font-weight:400}.apbct_settings_top_info__div{float:right;padding:0 20px 0 0;font-size:13px;position:relative}.apbct_settings_top_info__p{padding:0;margin:2px}.apbct_settings_top_info__btn{display:inline-flex;gap:10px}.apbct_hidden_section_nav_mob_btn{display:none;background-image:url(images/menu.svg);background-repeat:no-repeat;background-size:contain;background-position-y:center}.apbct_hidden_section_nav_mob_btn-close{display:none}.apbct_settings__footer{background:#c2c2c2;position:absolute;left:0;padding-bottom:30px;padding-left:21px;z-index:-1}.apbct_settings_top_info__sub_btn{display:flex;flex-wrap:wrap;gap:10px;margin:15px 0}.apbct_settings__key_line{display:flex;align-items:center;justify-content:flex-start;flex-direction:row}.apbct_settings__key_line__elements{margin-right:10px}.apbct_setting__key_line__buttons{margin:0}.apbct_setting__key_line__get_key_manual_chunk{margin:10px 0 10px 0;border:1px solid #d3d3d3;border-radius:3px;padding:10px;background:#fff}.apbct_settings__key_line__service_block{margin-left:10px}#apbct_settings__public_offer{margin-top:10px;display:flex;align-items:center}#cleantalk_apikey_wrapper{max-width:65%}.apcbt_contact_data_encoder__line{max-width:70%;display:flex;flex-wrap:wrap;flex-direction:row}.apbct_warning_red_point{display:inline-block;width:4px;height:4px;background:red;border-radius:100%;margin:0 10px 3px 3px;vertical-align:middle;position:relative}.apbct_warning_red_point::after{content:'';position:absolute;left:50%;top:50%;width:12px;height:12px;border:1.5px solid rgba(255,2,2,.65);border-radius:50%;animation:apbct_pulsate 1.2s ease-out infinite;opacity:.7;pointer-events:none;transform:translate(-50%,-50%)}#apbct_summary_and_support{display:flex;flex-wrap:wrap;width:-webkit-fill-available;border:1px solid #ddd;border-radius:3px;padding:10px;background:#ededed;margin-top:4em}#apbct_summary_and_support-left_side{width:69%;padding:0 20px 0 0}#apbct_summary_and_support-right_side{width:31%;padding:0 20px;border-left:1px solid #dcdcde}#apbct_summary_and_support-sides_wrap{display:flex;flex-direction:row;margin:10px 0 10px;width:100%}.apbct_summary_and_support-side_header{margin:.5em 0}.apbct_summary_and_support-inner_header{margin:2em 0 .5em;font-size:medium}.apbct_summary_and_support-inner_header::after{content:'';display:block;width:100%;height:1px;background:linear-gradient(90deg,#d3d3d357 0,rgba(211,211,211,.14) 10%,transparent 100%);margin-top:5px}.apbct_summary_and_support-support_buttons_wrapper{display:flex;flex-direction:column}#apbct_summary_and_support-create_user_button{display:inline-flex;flex-direction:row;align-items:center;justify-content:center}.apbct_summary_and_support-user_creation_result{background:#eee;margin-top:10px;padding:5px;border:1px solid #d3d3d3;display:none}.apbct_summary-list_of_items{display:flex;flex-direction:column}.apbct_summary_list_item{margin-bottom:2px}.apbct-green{color:green}.apbct-red{color:red}#apbct_negative_reports_table{width:100%;border-collapse:collapse;margin:10px 5px}#apbct_sending_report_div{display:flex;flex-direction:row;justify-content:flex-end;align-items:center;flex-wrap:nowrap}#apbct_sending_report_disabled_notice{margin-right:5px}.apbct-real-user-popup-img{align-self:start;margin:0!important;height:1.1em;vertical-align:initial}@keyframes apbct_pulsate{0%{transform:translate(-50%,-50%) scale(1);opacity:.7}100%{transform:translate(-50%,-50%) scale(1.5);opacity:0}}@media (max-width:768px){.apbct_settings_top_info__btn{display:inline-grid;width:100%;gap:5px}#apbct_settings__advanced_settings_inner,#apbct_settings__after_advanced_settings{width:100%}.apbct_settings-field_content--radio,.apbct_settings-field_wrapper>.apbct_settings-field_description{width:100%}.apbct_settings_top_info__sub_btn .apbct_bottom_links--left,.apbct_settings_top_info__sub_btn .apbct_bottom_links--other{margin-left:0;margin-right:0}#apbct_hidden_section_nav ul{display:none;background-color:#dadee3bd;margin:0;padding:10px;border-radius:3px;right:0;width:auto}#apbct_hidden_section_nav{right:0;min-width:167px}.apbct_setting_radio::before{height:6px!important;width:6px!important;margin:4px!important}.apbct_setting_checkbox::before{height:15px!important;width:15px!important;margin:0 -.05rem!important}.apbct_setting_checkbox,.apbct_setting_radio{height:16px!important;width:16px!important}.apbct_hidden_section_nav_mob_btn{display:block;width:32px;height:28px;right:20px;top:20px;position:fixed}.apbct_hidden_section_nav_mob_btn-close{display:block;position:relative;float:right;width:20px;height:22px;top:-5px;right:-5px;background-image:url(images/cancel.svg);background-repeat:no-repeat;background-size:contain;background-position-y:center;text-align:center}.apbct_long_desc{left:-2%!important;max-width:95%;margin-top:10%}.apbct_long_desc__angle{display:none}.ct_rate_block{max-width:240px;margin-right:20px}.apbct_settings__key_line{display:flex;align-items:flex-start;flex-direction:column;width:100%}.apbct_settings__key_line__elements{margin:5px 0 5px 0}#apbct_setting_apikey,.apbct_setting__key_line__buttons,.apbct_settings__key_line__elements{width:100%}#cleantalk_apikey_wrapper{max-width:100%}#apbct_settings__button_section{position:fixed;right:20px}.apcbt_contact_data_encoder__line{max-width:100%;margin-top:5px}#apbct_summary_and_support-right_side{border-top:1px solid #dcdcde;border-left:0;margin:35px 0 0;padding:0;width:-webkit-fill-available}#apbct_summary_and_support-left_side{border-top:1px solid #dcdcde;width:-webkit-fill-available}#apbct_summary_and_support-sides_wrap{flex-direction:column}}.apbct-trial-renew-fullpage{display:flex;position:fixed;width:stretch;top:0;bottom:0;overflow-y:auto;justify-content:center;align-items:flex-start;font-family:Inter,system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:#444;background-color:#f0f0f0;z-index:99}.apbct-trial-renew-fullpage-notice{padding:32px 64px 64px 64px!important;margin-top:5em!important;margin-bottom:5em!important}.apbct-trial-renew-fullpage-body{margin-top:32px;margin-left:32px}.apbct-banner-header{display:flex;justify-content:space-between}.apbct-trial-renew-fullpage-body .apbct-banner-button-wrapper{display:flex;margin:0}.apbct-trial-renew-fullpage-image{flex:1 1 0;min-width:0;max-width:576px;height:auto;object-fit:contain;margin:auto 0;align-self:flex-start}.apbct-banner-desc-block-row{line-height:22px}.apbct-banner-red-point{display:inline-block;width:8px;height:8px;background-color:#bb3323;border-radius:50%;margin-right:8px;vertical-align:middle}.apbct-banner-error{background-color:#fff!important;box-shadow:0 4px 15px #84848440!important;border-left-color:#bb3323!important}.apbct-banner-background-container{display:grid;max-width:644px;gap:16px;padding:32px;background-color:#f3f6f9;border-radius:8px}.apbct-banner-desc-block-title{font-size:18px;font-weight:700;line-height:22px;color:#0a0a0a;margin-bottom:8px}.apbct-banner-stat-value{margin-bottom:0;color:#444;vertical-align:middle}.apbct-banner-desc-block-text{font-size:14px;line-height:22px;color:#717182;margin-left:12px;margin-top:0;vertical-align:middle}.apbct-banner-desc-blocks{display:grid;gap:16px;flex:1 1 0;min-width:0}.apbct-banner-desc-blocks-content{display:flex;gap:72px;flex-wrap:wrap;justify-content:center;margin:32px 0}.apbct-banner-check{vertical-align:middle}.apbct-trial-renew-upgrade{display:none;text-align:center}.apbct-trial-renew-upgrade-link{font-size:16px;line-height:22px;letter-spacing:0;text-decoration:underline solid 0 #026e88!important;text-underline-offset:25%;color:#026e88!important}@media (max-width:1366px){.apbct-banner-header{display:grid;gap:16px}.apbct-banner-desc-blocks-content{display:grid;gap:38px;place-items:center}.apbct-trial-renew-upgrade{display:block}}@media (max-width:1200px){.apbct-banner-desc-blocks-content{gap:32px}}@media (max-width:782px){.apbct-trial-renew-fullpage{padding-top:50px;padding-bottom:50px}.apbct-trial-renew-fullpage-notice{padding:24px 24px 32px 24px!important}.apbct-trial-renew-fullpage-body{margin-top:20px;margin-left:0}.apbct-banner-desc-blocks-content{gap:24px}.apbct-banner-background-container{padding:20px}.apbct-trial-renew-fullpage-image{width:100%}}@media (max-width:480px){.apbct-trial-renew-fullpage-notice{padding:16px 12px 24px 12px!important}.apbct-banner-background-container{padding:16px}.apbct-banner-desc-blocks-content{gap:16px}.apbct-banner-desc-block-title{font-size:16px}} \ No newline at end of file +.apbct_settings-page{padding-right:10px}.apbct_settings-field_content,.cleantalk_link-auto,.cleantalk_link-manual,.ct-warning-test-failed,.ct_rate_block,.ct_settings_banner,i.animate-spin{display:inline-block}#apbctTopWarning{margin-bottom:5px}#apbctTopWarning h3{margin:10px 0 5px 0}#apbctTopWarning h4{margin:10px}#apbctTopWarning h4 span{margin-top:5px}.apbct_settings-subtitle{position:relative;top:-15px;margin:0}.apbct_settings-field_wrapper{margin:15px 0}.apbct_settings-field_wrapper--sub{margin-left:30px!important}.apbct_settings__label{margin-right:10px;font-size:17px;vertical-align:text-bottom}.apbct_settings-field_content{display:inline-block}.apbct_settings-field_content--radio,.apbct_settings-field_wrapper>.apbct_settings-field_description{width:70%;padding-bottom:10px}.apbct_settings-field_title--select,.apbct_settings-field_title--textarea{margin:0;width:210px;padding-right:10px;padding-bottom:10px;font-size:14px;vertical-align:top}.apbct_settings-field_title--with-help{width:auto;white-space:nowrap}.apbct_settings-field_title--radio{display:inline-block;margin:0;width:210px;padding-right:10px;font-size:14px;vertical-align:top}.apbct_input_text{min-width:255px;width:400px}.apbct_settings-long_description---show:hover{color:#aaa;cursor:pointer}.apbct_setting_textarea{min-width:300px}.cleantalk_link{text-decoration:none;font-size:13px;line-height:26px;margin:10px 0 0 0;padding:0 10px 1px;cursor:pointer;border-width:1px;border-style:solid;-webkit-appearance:none;white-space:nowrap;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.cleantalk_link-auto{background:#ccc;border-color:#999;-webkit-box-shadow:inset 0 1px 0 rgba(200,200,200,.5),0 1px 0 rgba(0,0,0,.15);box-shadow:inset 0 1px 0 rgba(200,200,200,.5),0 1px 0 rgba(0,0,0,.15);color:#000;display:inline-block;height:28px;-webkit-border-radius:2px;border-radius:2px}.cleantalk_link-auto:hover{color:#fff}.cleantalk_link-auto.cleantalk_link_text_center{text-align:center}.cleantalk_link-manual{background:#2ea2cc;border-color:#0074a2;-webkit-box-shadow:inset 0 1px 0 rgba(120,200,230,.5),0 1px 0 rgba(0,0,0,.15);box-shadow:inset 0 1px 0 rgba(120,200,230,.5),0 1px 0 rgba(0,0,0,.15);color:#fff;display:inline-block;-webkit-border-radius:3px;border-radius:3px;text-align:center}.cleantalk_link-manual:hover{color:#000}.cleantalk_link[disabled=disabled]{background:#5d9db5;color:#000}.apbct_status_icon{vertical-align:text-bottom;margin:0 5px 0 8px}.apbct-icon-upload-cloud{margin-left:3px}a.ct_support_link{color:#666;margin-right:.5em;font-size:10pt;font-weight:400}.ct-warning-test-failed{display:inline-block;position:relative;padding:5px;margin:4px;border:3px solid #f03232;border-radius:5px;background-color:#ffc8c8}.ct_settings_banner{text-align:right;display:inline-block;width:100%;margin:1em 0;vertical-align:top}#ct_translate_plugin{margin-left:0}.ct_rate_block{display:inline-block;width:370px;margin-right:3em;padding:.8em .8em 15px .8em;text-align:center;border:1px dashed #666}#ct_translate_plugin .apbct_button_rate{margin-bottom:10px}.apbct_long_desc{position:absolute;background:#5a5a5a;min-width:80px;min-height:80px;max-width:500px;padding:10px;color:#fff;z-index:10}.apbct_long_desc a{color:#78c8e6}i.animate-spin{-moz-animation:spin 2s infinite linear;-o-animation:spin 2s infinite linear;-webkit-animation:spin 2s infinite linear;animation:spin 2s infinite linear;display:inline-block;margin:0 auto;font-size:25px;line-height:20px;color:#78c8e6;margin:25px}@keyframes spin{to{transform:rotate(359deg)}}.apbct_long_desc__cancel{position:absolute;top:5px;right:5px;color:rgba(255,255,255,.5)}.apbct_long_desc__cancel:hover{color:#fff}.apbct_long_desc__angle{position:absolute;top:5px;left:-17px;width:10px;height:10px;background:#5a5a5a;-webkit-transform:rotate(135deg);-ms-transform:rotate(135deg);transform:rotate(135deg);-webkit-transform-origin:100% 100%;-ms-transform-origin:100% 100%;transform-origin:100% 100%}.apbct_long_desc__title{color:#78c8e6;margin:0}.--hide{display:none}.apbct_preloader_button{height:15px;margin-left:5px;vertical-align:text-top;display:none}.--invisible{visibility:hidden}.apbct_preloader{height:1em;width:1em;margin-left:.5em;display:inline-block}.key_changed_sync{font-size:1.5em;line-height:2em;vertical-align:middle}.key_changed_success{font-size:1.5em;line-height:2em;vertical-align:middle}.--upper-case{text-transform:uppercase}#cleantalk-modal-content{text-align:center}#cleantalk-modal-content>*{display:block;width:100%}.cleantalk-confirm-modal_header{font-size:15px;font-weight:500}.cleantalk-confirm-modal_text-block{padding:10px 0}.cleantalk-confirm-modal_buttons-block{display:flex!important;gap:10px;justify-content:center}button.ct_support_link{border:none;background:0 0;color:#666;text-decoration:underline;cursor:pointer}.apbct-btn-as-link{padding:0;margin:0;vertical-align:baseline;color:gray;border:0 none;border-bottom:1px solid;cursor:pointer}#apbct-account-email[contenteditable=true]{padding:6px;background-color:#fff;border:1px solid #ccc}button[value=save_changes]:disabled{color:#2271b1;border-color:#2271b1;background:#f6f7f7}#apbct_settings__advanced_settings{position:relative}#apbct_settings__advanced_settings_inner{width:70%}#apbct_hidden_section_nav{position:absolute;top:0;right:0;width:200px}#apbct_hidden_section_nav ul{z-index:9999;width:100%;top:40px}.apbct_settings__position_main_save_button{text-align:right;margin-right:40px}#apbct_settings__after_advanced_settings{margin-bottom:20px;width:70%}#apbct_settings__button_section{position:static;z-index:9999;padding-bottom:40px;bottom:0}.apbct_highlighted{outline-offset:5px;outline-color:red;outline-width:3px!important;outline-style:solid!important}.apbct_notice_inner{display:flex;margin-top:10px!important}.apbct_notification__advanced_settings{margin:20px 0;font-weight:400}.apbct_settings_top_info__div{float:right;padding:0 20px 0 0;font-size:13px;position:relative}.apbct_settings_top_info__p{padding:0;margin:2px}.apbct_settings_top_info__btn{display:inline-flex;gap:10px}.apbct_hidden_section_nav_mob_btn{display:none;background-image:url(images/menu.svg);background-repeat:no-repeat;background-size:contain;background-position-y:center}.apbct_hidden_section_nav_mob_btn-close{display:none}.apbct_settings__footer{background:#c2c2c2;position:absolute;left:0;padding-bottom:30px;padding-left:21px;z-index:-1}.apbct_settings_top_info__sub_btn{display:flex;flex-wrap:wrap;gap:10px;margin:15px 0}.apbct_settings__key_line{display:flex;align-items:center;justify-content:flex-start;flex-direction:row}.apbct_settings__key_line__elements{margin-right:10px}.apbct_setting__key_line__buttons{margin:0}.apbct_setting__key_line__get_key_manual_chunk{margin:10px 0 10px 0;border:1px solid #d3d3d3;border-radius:3px;padding:10px;background:#fff}.apbct_settings__key_line__service_block{margin-left:10px}#apbct_settings__public_offer{margin-top:10px;display:flex;align-items:center}#cleantalk_apikey_wrapper{max-width:65%}.apcbt_contact_data_encoder__line{max-width:70%;display:flex;flex-wrap:wrap;flex-direction:row}.apbct_warning_red_point{display:inline-block;width:4px;height:4px;background:red;border-radius:100%;margin:0 10px 3px 3px;vertical-align:middle;position:relative}.apbct_warning_red_point::after{content:'';position:absolute;left:50%;top:50%;width:12px;height:12px;border:1.5px solid rgba(255,2,2,.65);border-radius:50%;animation:apbct_pulsate 1.2s ease-out infinite;opacity:.7;pointer-events:none;transform:translate(-50%,-50%)}#apbct_summary_and_support{display:flex;flex-wrap:wrap;width:-webkit-fill-available;border:1px solid #ddd;border-radius:3px;padding:10px;background:#ededed;margin-top:4em}#apbct_summary_and_support-left_side{width:69%;padding:0 20px 0 0}#apbct_summary_and_support-right_side{width:31%;padding:0 20px;border-left:1px solid #dcdcde}#apbct_summary_and_support-sides_wrap{display:flex;flex-direction:row;margin:10px 0 10px;width:100%}.apbct_summary_and_support-side_header{margin:.5em 0}.apbct_summary_and_support-inner_header{margin:2em 0 .5em;font-size:medium}.apbct_summary_and_support-inner_header::after{content:'';display:block;width:100%;height:1px;background:linear-gradient(90deg,#d3d3d357 0,rgba(211,211,211,.14) 10%,transparent 100%);margin-top:5px}.apbct_summary_and_support-support_buttons_wrapper{display:flex;flex-direction:column}#apbct_summary_and_support-create_user_button{display:inline-flex;flex-direction:row;align-items:center;justify-content:center}.apbct_summary_and_support-user_creation_result{background:#eee;margin-top:10px;padding:5px;border:1px solid #d3d3d3;display:none}.apbct_summary-list_of_items{display:flex;flex-direction:column}.apbct_summary_list_item{margin-bottom:2px}.apbct-green{color:green}.apbct-red{color:red}#apbct_negative_reports_table{width:100%;border-collapse:collapse;margin:10px 5px}#apbct_sending_report_div{display:flex;flex-direction:row;justify-content:flex-end;align-items:center;flex-wrap:nowrap}#apbct_sending_report_disabled_notice{margin-right:5px}.apbct-real-user-popup-img{align-self:start;margin:0!important;height:1.1em;vertical-align:initial}@keyframes apbct_pulsate{0%{transform:translate(-50%,-50%) scale(1);opacity:.7}100%{transform:translate(-50%,-50%) scale(1.5);opacity:0}}@media (max-width:768px){.apbct_settings_top_info__btn{display:inline-grid;width:100%;gap:5px}#apbct_settings__advanced_settings_inner,#apbct_settings__after_advanced_settings{width:100%}.apbct_settings-field_content--radio,.apbct_settings-field_wrapper>.apbct_settings-field_description{width:100%}.apbct_settings_top_info__sub_btn .apbct_bottom_links--left,.apbct_settings_top_info__sub_btn .apbct_bottom_links--other{margin-left:0;margin-right:0}#apbct_hidden_section_nav ul{display:none;background-color:#dadee3bd;margin:0;padding:10px;border-radius:3px;right:0;width:auto}#apbct_hidden_section_nav{right:0;min-width:167px}.apbct_setting_radio::before{height:6px!important;width:6px!important;margin:4px!important}.apbct_setting_checkbox::before{height:15px!important;width:15px!important;margin:0 -.05rem!important}.apbct_setting_checkbox,.apbct_setting_radio{height:16px!important;width:16px!important}.apbct_hidden_section_nav_mob_btn{display:block;width:32px;height:28px;right:20px;top:20px;position:fixed}.apbct_hidden_section_nav_mob_btn-close{display:block;position:relative;float:right;width:20px;height:22px;top:-5px;right:-5px;background-image:url(images/cancel.svg);background-repeat:no-repeat;background-size:contain;background-position-y:center;text-align:center}.apbct_long_desc{left:-2%!important;max-width:95%;margin-top:10%}.apbct_long_desc__angle{display:none}.ct_rate_block{max-width:240px;margin-right:20px}.apbct_settings__key_line{display:flex;align-items:flex-start;flex-direction:column;width:100%}.apbct_settings__key_line__elements{margin:5px 0 5px 0}#apbct_setting_apikey,.apbct_setting__key_line__buttons,.apbct_settings__key_line__elements{width:100%}#cleantalk_apikey_wrapper{max-width:100%}#apbct_settings__button_section{position:fixed;right:20px}.apcbt_contact_data_encoder__line{max-width:100%;margin-top:5px}#apbct_summary_and_support-right_side{border-top:1px solid #dcdcde;border-left:0;margin:35px 0 0;padding:0;width:-webkit-fill-available}#apbct_summary_and_support-left_side{border-top:1px solid #dcdcde;width:-webkit-fill-available}#apbct_summary_and_support-sides_wrap{flex-direction:column}}.apbct-trial-renew-fullpage{display:flex;position:fixed;width:stretch;top:0;bottom:0;overflow-y:auto;justify-content:center;align-items:flex-start;font-family:Inter,system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:#444;background-color:#f0f0f0;z-index:99}.apbct-trial-renew-fullpage-notice{padding:32px 64px 64px 64px!important;margin-top:5em!important;margin-bottom:5em!important}.apbct-trial-renew-fullpage-body{margin-top:32px;margin-left:32px}.apbct-banner-header{display:flex;justify-content:space-between}.apbct-trial-renew-fullpage-body .apbct-banner-button-wrapper{display:flex;margin:0}.apbct-trial-renew-fullpage-image{flex:1 1 0;min-width:0;max-width:576px;height:auto;object-fit:contain;margin:auto 0;align-self:flex-start}.apbct-banner-desc-block-row{line-height:22px}.apbct-banner-red-point{display:inline-block;width:8px;height:8px;background-color:#bb3323;border-radius:50%;margin-right:8px;vertical-align:middle}.apbct-banner-error{background-color:#fff!important;box-shadow:0 4px 15px #84848440!important;border-left-color:#bb3323!important}.apbct-banner-background-container{display:grid;max-width:644px;gap:16px;padding:32px;background-color:#f3f6f9;border-radius:8px}.apbct-banner-desc-block-title{font-size:18px;font-weight:700;line-height:22px;color:#0a0a0a;margin-bottom:8px}.apbct-banner-stat-value{margin-bottom:0;color:#444;vertical-align:middle}.apbct-banner-desc-block-text{font-size:14px;line-height:22px;color:#717182;margin-left:12px;margin-top:0;vertical-align:middle}.apbct-banner-desc-blocks{display:grid;gap:16px;flex:1 1 0;min-width:0}.apbct-banner-desc-blocks-content{display:flex;gap:72px;flex-wrap:wrap;justify-content:center;margin:32px 0}.apbct-banner-check{vertical-align:middle}.apbct-trial-renew-upgrade{display:none;text-align:center}.apbct-trial-renew-upgrade-link{font-size:16px;line-height:22px;letter-spacing:0;text-decoration:underline solid 0 #026e88!important;text-underline-offset:25%;color:#026e88!important}@media (max-width:1366px){.apbct-banner-header{display:grid;gap:16px}.apbct-banner-desc-blocks-content{display:grid;gap:38px;place-items:center}.apbct-trial-renew-upgrade{display:block}}@media (max-width:1200px){.apbct-banner-desc-blocks-content{gap:32px}}@media (max-width:782px){.apbct-trial-renew-fullpage{padding-top:50px;padding-bottom:50px}.apbct-trial-renew-fullpage-notice{padding:24px 24px 32px 24px!important}.apbct-trial-renew-fullpage-body{margin-top:20px;margin-left:0}.apbct-banner-desc-blocks-content{gap:24px}.apbct-banner-background-container{padding:20px}.apbct-trial-renew-fullpage-image{width:100%}}@media (max-width:480px){.apbct-trial-renew-fullpage-notice{padding:16px 12px 24px 12px!important}.apbct-banner-background-container{padding:16px}.apbct-banner-desc-blocks-content{gap:16px}.apbct-banner-desc-block-title{font-size:16px}} \ No newline at end of file diff --git a/css/cleantalk-trp.min.css b/css/cleantalk-trp.min.css index 28f754d9b..c250792ad 100644 --- a/css/cleantalk-trp.min.css +++ b/css/cleantalk-trp.min.css @@ -1 +1 @@ -.apbct-real-user-wrapper{display:inline-flex;color:#000!important;flex-wrap:nowrap;justify-content:center;flex-direction:row;align-items:center}.apbct-real-user-wrapper-woo{display:inline;align-items:center;color:#444!important;font-size:14px}.apbct-real-user-author-name{display:inline-flex}.apbct-real-user-badge{display:inline-flex;padding-left:6px;cursor:pointer;position:relative}.apbct-real-user-popup{position:absolute;padding:8px;font-weight:400;color:#000!important;background:#fff;border:1px #ccc solid;border-radius:4px;box-shadow:5px 5px 24px -11px #444;z-index:-1;cursor:default;opacity:0;transition-property:opacity,z-index}.apbct-real-user-popup.visible{z-index:1;opacity:1}.apbct-real-user-title{display:grid;gap:4px!important}.apbct-real-user-popup-content_row{display:flex;flex-direction:column;gap:1px}@media (min-width:768px){.apbct-real-user-popup-content_row{white-space:nowrap}}.apbct-real-user-popup-content_row *{color:grey;font-style:italic}.apbct-real-user-popup-content_row strong{color:initial;font-style:initial}.apbct-real-user-popup-img{align-self:start;margin:0!important;height:.9em;vertical-align:sub}.apbct-real-user-popup-header{font-weight:bolder;margin:2px!important} \ No newline at end of file +.apbct-real-user-wrapper{display:inline-flex;color:#000!important;flex-wrap:nowrap;justify-content:center;flex-direction:row;align-items:center}.apbct-real-user-wrapper-woo{display:inline;align-items:center;color:#444!important;font-size:14px}.apbct-real-user-author-name{display:inline-flex}.apbct-real-user-badge{display:inline-flex;padding-left:6px;cursor:pointer;position:relative}.apbct-real-user-popup{position:absolute;padding:8px;font-weight:400;color:#000!important;background:#fff;border:1px #ccc solid;border-radius:4px;box-shadow:5px 5px 24px -11px #444;z-index:-1;cursor:default;opacity:0;transition-property:opacity,z-index}.apbct-real-user-popup.visible{z-index:1;opacity:1}.apbct-real-user-title{display:grid;gap:4px!important}.apbct-real-user-popup-content_row{display:flex;flex-direction:column;gap:1px}.apbct-real-user-popup-content_row *{color:grey;font-style:italic}.apbct-real-user-popup-content_row strong{color:initial;font-style:initial}.apbct-real-user-popup-img{align-self:start;margin:0!important;height:.9em;vertical-align:sub}.apbct-real-user-popup-header{font-weight:bolder;margin:2px!important} \ No newline at end of file diff --git a/css/src/cleantalk-admin-settings-page.css b/css/src/cleantalk-admin-settings-page.css index 8b307d064..2922bd8a6 100644 --- a/css/src/cleantalk-admin-settings-page.css +++ b/css/src/cleantalk-admin-settings-page.css @@ -59,6 +59,10 @@ i.animate-spin { font-size: 14px; vertical-align: top; } +.apbct_settings-field_title--with-help{ + width: auto; + white-space: nowrap; +} .apbct_settings-field_title--radio{ display: inline-block; margin: 0; diff --git a/css/src/cleantalk-trp.css b/css/src/cleantalk-trp.css index ea56545be..103e75da1 100644 --- a/css/src/cleantalk-trp.css +++ b/css/src/cleantalk-trp.css @@ -55,11 +55,6 @@ flex-direction: column; gap: 1px; } -@media (min-width: 768px) { - .apbct-real-user-popup-content_row { - white-space: nowrap; - } -} .apbct-real-user-popup-content_row * { color: grey; diff --git a/inc/apbct-sync-react.php b/inc/apbct-sync-react.php index a9f78ae0f..4e107669b 100644 --- a/inc/apbct-sync-react.php +++ b/inc/apbct-sync-react.php @@ -42,7 +42,11 @@ function apbct_react_access_key_check() ); } - $apbct->errorDeleteAll(true); + $clear_all_blogs = APBCT_WPMS + && is_main_site() + && isset($apbct->network_settings['multisite__work_mode']) + && (int) $apbct->network_settings['multisite__work_mode'] === 2; + apbct_settings__clear_errors($clear_all_blogs); $account_is_ok = (bool) ct_account_status_check($apbct->settings['apikey']); $connection_error = ! empty($apbct->errors['account_check']) diff --git a/inc/cleantalk-admin.php b/inc/cleantalk-admin.php index f52e3e67d..2c5695653 100644 --- a/inc/cleantalk-admin.php +++ b/inc/cleantalk-admin.php @@ -48,7 +48,7 @@ function apbct_admin_set_cookie_for_anti_bot() echo ''; } } diff --git a/inc/cleantalk-common.php b/inc/cleantalk-common.php index d60727c53..5967935cb 100644 --- a/inc/cleantalk-common.php +++ b/inc/cleantalk-common.php @@ -5,6 +5,7 @@ use Cleantalk\Antispam\CleantalkResponse; use Cleantalk\ApbctWP\API; use Cleantalk\ApbctWP\BaseCall\DefaultParams; +use Cleantalk\ApbctWP\BotDetectorService; use Cleantalk\ApbctWP\CleantalkSettingsTemplates; use Cleantalk\ApbctWP\Constant; use Cleantalk\ApbctWP\Cron; @@ -744,7 +745,7 @@ function apbct_get_pixel_url($direct_call = false) */ function apbct_email_check_before_post() { - $email = trim(TT::toString(Post::get('email'))); + $email = trim(TT::toString(Post::get('email')), " \n\r\t\v\x00"); if ( $email ) { $result = \Cleantalk\ApbctWP\API::methodEmailCheck($email); @@ -762,7 +763,7 @@ function apbct_email_check_before_post() function apbct_email_check_exist_post() { global $apbct; - $email = trim(TT::toString(Post::get('email'))); + $email = trim(TT::toString(Post::get('email')), " \n\r\t\v\x00"); $api_key = $apbct->api_key; $brandname = $apbct->data['wl_mode_enabled'] ? $apbct->data['wl_brandname'] : 'Anti-Spam by CleanTalk'; if ( $email && $api_key ) { @@ -1152,7 +1153,7 @@ function ct_get_fields_any($arr, $email = '', $nickname = '') foreach ( $nickname as $value ) { $nickname_str .= ($value ? $value . " " : ""); } - $nickname = trim($nickname_str); + $nickname = trim($nickname_str, " \n\r\t\v\x00"); } return ct_gfa($arr, TT::toString($email), TT::toString($nickname)); @@ -1813,156 +1814,41 @@ function apbct_get_event_token($params) } /** - * Do prepare exclusions for skippping bot-detector event token field. + * Prepare exclusions for skippping bot-detector event token field. + * @deprecated since 6.88, use BotDetectorService::getPreparedExclusions() instead * @return string JSOn */ function apbct__bot_detector_get_prepared_exclusion() { - global $apbct; - $bot_detector_exclusions = array(); - - //start exclusion there - - //todo if do need to add a built-ib exclusion, use $exlusion_format - //set regexp to chek within attributes - // $exlusion_format = array( - // 'exclusion_id' => '', - // 'signs_to_check' => array( - // 'form_attributes' => '', - // 'form_children_attributes' => '', - // 'form_parent_attributes' => '' - // ) - // ); - if ($apbct->settings['exclusions__bot_detector']) { - $bot_detector_exclusions = array_merge( - $bot_detector_exclusions, - apbct__bot_detector_get_custom_exclusion_from_settings() - ); - } - - //start validate - $bot_detector_exclusions_valid = array(); - foreach ($bot_detector_exclusions as $exclusion) { - if ( - empty($exclusion['exclusion_id']) || - ( - empty($exclusion['signs_to_check']['form_attributes']) && - empty($exclusion['signs_to_check']['form_children_attributes']) && - empty($exclusion['signs_to_check']['form_parent_attributes']) - ) - ) { - continue; - } - $bot_detector_exclusions_valid[] = $exclusion; - } - - //prepare for early localize - $bot_detector_exclusions_valid = json_encode($bot_detector_exclusions_valid); - return $bot_detector_exclusions_valid !== false ? $bot_detector_exclusions_valid : '{}'; + return BotDetectorService::getPreparedExclusions(); } +/** + * @deprecated since 6.88, use BotDetectorService::getFrontendDataLog() instead + * @return string + */ function apbct__bot_detector_get_fired_exclusions() { - return Cookie::get('ct_bot_detector_form_exclusion'); + return BotDetectorService::getFiredExclusions(); } /** * Return bot detector frontend data log from Alt Sessions if data found. * Format: JSON. - * + * @deprecated since 6.88, use BotDetectorService::getFrontendDataLog() instead * @return string JSON encoded bot detector frontend data log. */ function apbct__bot_detector_get_fd_log() { - $result = array( - 'plugin_status' => 'OK', - 'error_msg' => '', - 'frontend_data_log' => '' - ); - // Initialize result array with default values - - if (Constant::is(Constant::APBCT_SERVICE__DO_NOT_COLLECT_FRONTEND_DATA_LOGS)) { - $result['plugin_status'] = 'OK'; - $result['error_msg'] = 'bot detector logs collection is disabled via constant definition'; - return json_encode($result); - } - - try { - if ( ! apbct__is_bot_detector_enabled() ) { - throw new \Exception('bot detector library usage is disabled'); - } - // Retrieve bot detector frontend data log from Alt Sessions - $alt_sessions_fd_log = AltSessions::get('ct_bot_detector_frontend_data_log'); - // Check if the retrieved data is a string - if ( !is_string($alt_sessions_fd_log) || '' === $alt_sessions_fd_log ) { - throw new \Exception('no log found in alt sessions'); - } - // Encode the retrieved data to JSON format - $param_bot_detector_fd_log = json_decode($alt_sessions_fd_log, true); - // Check if the JSON encoding was successful - if ( empty($param_bot_detector_fd_log) ) { - throw new \Exception('can not decode data from alt sessions'); - } - } catch (Exception $e) { - $result['plugin_status'] = 'ERROR'; - $result['error_msg'] = $e->getMessage(); - return json_encode($result); - } - $result['frontend_data_log'] = $param_bot_detector_fd_log; - // Return the result as a JSON encoded string - return json_encode($result); -} - -function apbct__bot_detector_get_custom_exclusion_from_settings() -{ - global $apbct; - - $exlusion_format = array( - 'exclusion_id' => '', - 'signs_to_check' => array( - 'form_attributes' => '', - 'form_children_attributes' => '', - 'form_parent_attributes' => '' - ) - ); - - $exclusions = array(); - if (!$apbct->settings['exclusions__bot_detector']) { - return $exclusions; - } - - foreach ($exlusion_format['signs_to_check'] as $sign => $_val) { - $setting_name = 'exclusions__bot_detector__' . $sign; - if (!empty($apbct->settings[$setting_name])) { - $regexps = explode(',', $apbct->settings[$setting_name]); - for ( $i = 0; $i < count($regexps); $i++ ) { - $form_exclusion = $exlusion_format; - $form_exclusion['exclusion_id'] = 'exclusion_' . $i; - $form_exclusion['signs_to_check'][$sign] = $regexps[$i]; - $exclusions[] = $form_exclusion; - } - } - } - return $exclusions; + return BotDetectorService::getFrontendDataLog(); } /** * Check if Bot-Detector is enabled/disabled - * + * @deprecated since 6.88, use BotDetectorService::isEnabled() instead * @return bool */ function apbct__is_bot_detector_enabled() { - global $apbct; - - // Constant is preferred - if ( Constant::is(Constant::APBCT_SERVICE__BOT_DETECTOR_ENABLED) ) { - return (bool) Constant::getValue(Constant::APBCT_SERVICE__BOT_DETECTOR_ENABLED); - } - // Check by $apbct->data - if ( isset($apbct->data['bot_detector_enabled']) ) { - return (bool) $apbct->data['bot_detector_enabled']; - } - // By default - enabled - return true; + return BotDetectorService::isEnabled(); } diff --git a/inc/cleantalk-public-integrations.php b/inc/cleantalk-public-integrations.php index b22c6df36..ace1bd880 100644 --- a/inc/cleantalk-public-integrations.php +++ b/inc/cleantalk-public-integrations.php @@ -178,7 +178,7 @@ function ct_woocommerce_wishlist_check($args) $subject = ''; $email = $args['wishlist_owner_email']; if ( $args['wishlist_first_name'] !== '' || $args['wishlist_last_name'] !== '' ) { - $nickname = trim($args['wishlist_first_name'] . " " . $args['wishlist_last_name']); + $nickname = trim($args['wishlist_first_name'] . " " . $args['wishlist_last_name'], " \n\r\t\v\x00"); } else { $nickname = ''; } diff --git a/inc/cleantalk-public.php b/inc/cleantalk-public.php index c9a1bb273..d141014c2 100644 --- a/inc/cleantalk-public.php +++ b/inc/cleantalk-public.php @@ -1,6 +1,7 @@ pixel_url = apbct_get_pixel_url(true); } - // Localize data if ( ! apbct_exclusions_check__url() ) { if (Constant::is(Constant::APBCT_SERVICE__PLACE_PUBLIC_JS_SCRIPTS_IN_FOOTER, true)) { @@ -982,7 +982,7 @@ function apbct_js_test($check_js_value = '', $is_cookie = false) ) { $js_key = $is_cookie && $apbct->data['cookies_type'] === 'alternative' ? Cookie::get('ct_checkjs') - : trim($check_js_value); + : trim($check_js_value, " \n\r\t\v\x00"); // Check static key if ( @@ -1302,13 +1302,13 @@ function apbct_enqueue_and_localize_public_scripts() ApbctEnqueue::getInstance()->css('cleantalk-public.css'); } +/** + * @deprecated since 6.88, use \Cleantalk\ApbctWP\BotDetectorService::isNoScripFlow() instead + * @return bool + */ function apbct_bot_detector_scripts_exclusion() { - if (apbct_is_plugin_active('oxygen/functions.php') && Get::get('ct_builder') === 'true') { - return true; - } - - return false; + return BotDetectorService::isNoScripFlow(); } diff --git a/inc/cleantalk-settings.php b/inc/cleantalk-settings.php index cea88f860..69b0ca5ea 100644 --- a/inc/cleantalk-settings.php +++ b/inc/cleantalk-settings.php @@ -659,7 +659,8 @@ function apbct_settings__set_fields() 'data__email_decoder_obfuscation_mode', 'data__email_decoder_obfuscation_custom_text', 'data__email_decoder_encode_phone_numbers', - 'data__email_decoder_encode_email_addresses' + 'data__email_decoder_encode_email_addresses', + 'data__email_decoder_excluded_strings' ), 'long_description' => true, ), @@ -676,6 +677,14 @@ function apbct_settings__set_fields() 'parent' => 'data__email_decoder', 'long_description' => true, ), + 'data__email_decoder_excluded_strings' => array( + 'type' => 'textarea', + 'title' => __('Do not encode these contacts', 'cleantalk-spam-protect'), + 'description' => ContactsEncoder::getExcludedStringsDescription(), + 'parent' => 'data__email_decoder', + 'class' => 'apbct_settings-field_wrapper--sub', + 'long_description' => true, + ), 'data__email_decoder_obfuscation_mode' => array( 'title' => __('Encoder obfuscation mode', 'cleantalk-spam-protect'), 'description' => ContactsEncoder::getObfuscationModesDescription(), @@ -2382,6 +2391,7 @@ function apbct_settings__validate($incoming_settings) 'data__email_decoder_obfuscation_mode', 'data__email_decoder_obfuscation_custom_text', 'data__email_decoder_buffer', + 'data__email_decoder_excluded_strings', ); $incoming_settings = apbct_settings__keep_settings_state_values( $incoming_settings, @@ -2397,12 +2407,24 @@ function apbct_settings__validate($incoming_settings) // Set missing network settings from default. $stored_network_options = get_site_option($apbct->option_prefix . '_network_settings', array()); + $incoming_work_mode = isset($incoming_settings['multisite__work_mode']) + ? $incoming_settings['multisite__work_mode'] + : null; $incoming_settings = apbct_settings__set_missed_network_settings( $incoming_settings, is_array($stored_network_options) ? $stored_network_options : array(), $apbct->default_network_settings ); + if ( APBCT_WPMS && is_main_site() && $incoming_work_mode !== null ) { + $previous_work_mode = isset($apbct->network_settings['multisite__work_mode']) + ? (int) $apbct->network_settings['multisite__work_mode'] + : 0; + if ( $previous_work_mode !== (int) $incoming_work_mode ) { + apbct_settings__clear_errors(true); + } + } + /** * -- SFW rules -- */ @@ -2450,7 +2472,7 @@ function apbct_settings__validate($incoming_settings) $predefined_key = Constant::getValue(Constant::APBCT_SERVICE__SELF_OWNED_ACCESS_KEY, false); - $incoming_settings['apikey'] = ! empty($incoming_settings['apikey']) ? trim($incoming_settings['apikey']) : ''; + $incoming_settings['apikey'] = ! empty($incoming_settings['apikey']) ? trim($incoming_settings['apikey'], " \n\r\t\v\x00") : ''; $incoming_settings['apikey'] = $predefined_key !== false ? $predefined_key : $incoming_settings['apikey']; $incoming_settings['apikey'] = ! is_main_site() && $apbct->white_label && $apbct->settings['apikey'] ? $apbct->settings['apikey'] : $incoming_settings['apikey']; $incoming_settings['apikey'] = is_main_site() || $apbct->allow_custom_key || $apbct->white_label ? $incoming_settings['apikey'] : $apbct->network_settings['apikey']; @@ -2470,7 +2492,7 @@ function apbct_settings__validate($incoming_settings) // Sanitize setting values foreach ( $incoming_settings as &$setting ) { if ( is_string($setting) ) { - $setting = preg_replace('/[<"\'>]/', '', trim($setting)); + $setting = preg_replace('/[<"\'>]/', '', trim($setting, " \n\r\t\v\x00")); } // Make HTML code inactive } @@ -2666,7 +2688,7 @@ function apbct_settings__validate($incoming_settings) // compare non-main site blog key with the validating key $blog_settings = get_option('cleantalk_settings'); $key_from_blog_settings = !empty($blog_settings['apikey']) ? $blog_settings['apikey'] : ''; - if ( isset($incoming_settings['apikey']) && (trim($incoming_settings['apikey']) !== trim($key_from_blog_settings)) ) { + if ( isset($incoming_settings['apikey']) && (trim($incoming_settings['apikey'], " \n\r\t\v\x00") !== trim($key_from_blog_settings, " \n\r\t\v\x00")) ) { $blog_key_changed = true; } $apbct->data['key_changed'] = empty($blog_key_changed) ? false : $blog_key_changed; @@ -2704,6 +2726,12 @@ function apbct_settings__validate($incoming_settings) $incoming_settings['data__email_decoder_obfuscation_custom_text'] = ContactsEncoder::getDefaultReplacingText(); } + $incoming_settings['data__email_decoder_excluded_strings'] = apbct_settings__sanitize__excluded_contact_strings( + isset($incoming_settings['data__email_decoder_excluded_strings']) + ? $incoming_settings['data__email_decoder_excluded_strings'] + : '' + ); + //sync discussion and plugin settings if (isset($incoming_settings['cleantalk_allowed_moderation'])) { update_option('cleantalk_allowed_moderation', TT::toString($incoming_settings['cleantalk_allowed_moderation'], '0')); @@ -2717,6 +2745,40 @@ function apbct_settings__validate($incoming_settings) return $incoming_settings; } +/** + * Clear plugin errors on the current site. + * When $all_blogs is true on WPMS, also wipe errors on every blog. + * + * @param bool $all_blogs + * + * @return void + */ +function apbct_settings__clear_errors($all_blogs = false) +{ + global $apbct, $wpdb; + + $apbct->errorDeleteAll(true); + + if ( ! $all_blogs || ! APBCT_WPMS ) { + return; + } + + $option_name = $apbct->option_prefix . '_errors'; + $current_blog_id = get_current_blog_id(); + $wp_blogs = $wpdb->get_results('SELECT blog_id FROM ' . $wpdb->blogs, OBJECT_K); + + if ( ! is_array($wp_blogs) ) { + return; + } + + foreach ( $wp_blogs as $blog ) { + if ( (int) $blog->blog_id === (int) $current_blog_id ) { + continue; + } + update_blog_option($blog->blog_id, $option_name, array()); + } +} + function apbct_settings__sync($direct_call = false) { if ( ! $direct_call ) { @@ -2734,8 +2796,12 @@ function apbct_settings__sync($direct_call = false) die(json_encode($out)); } - //Clearing all errors - $apbct->errorDeleteAll(true); + // Clearing all errors. Mutual Access Key (mode 2): wipe leftover banners on every blog. + $clear_all_blogs = APBCT_WPMS + && is_main_site() + && isset($apbct->network_settings['multisite__work_mode']) + && (int) $apbct->network_settings['multisite__work_mode'] === 2; + apbct_settings__clear_errors($clear_all_blogs); // Feedback with app_agent ct_send_feedback('0:' . APBCT_AGENT); // 0 - request_id, agent version. @@ -2910,7 +2976,7 @@ function apbct_settings__save_key($apikey = '', $direct_call = false) } } - $apikey = trim($apikey); + $apikey = trim($apikey, " \n\r\t\v\x00"); $apikey = preg_match('/^[a-z\d]*$/', $apikey) ? $apikey : $apbct->settings['apikey']; if ( APBCT_WPMS && ! is_main_site() && (int) $apbct->network_settings['multisite__work_mode'] === 2 ) { @@ -3024,8 +3090,8 @@ function apbct_settings__get_key_auto($direct_call = false) } if ( ! empty($result['auth_key']) && apbct_api_key__is_correct($result['auth_key']) ) { - $apbct->data['key_changed'] = trim($result['auth_key']) !== $apbct->settings['apikey']; - $apbct->settings['apikey'] = trim($result['auth_key']); + $apbct->data['key_changed'] = trim($result['auth_key'], " \n\r\t\v\x00") !== $apbct->settings['apikey']; + $apbct->settings['apikey'] = trim($result['auth_key'], " \n\r\t\v\x00"); } $templates = ''; @@ -3187,7 +3253,7 @@ function apbct_settings__sanitize__exclusions($exclusions, $regexp = false, $url foreach ($exclusions as $exclusion) { //Cut exclusion if more than 128 symbols gained $sanitized_exclusion = substr($exclusion, 0, 128); - $sanitized_exclusion = trim($sanitized_exclusion); + $sanitized_exclusion = trim($sanitized_exclusion, " \n\r\t\v\x00"); if ( ! empty($sanitized_exclusion) ) { if ( $regexp ) { @@ -3214,6 +3280,32 @@ function apbct_settings__sanitize__exclusions($exclusions, $regexp = false, $url } } +/** + * Sanitize the Contacts Encoder skip-list: one value per line, max 20 items, 128 chars each. + * + * @param mixed $exclusions + * + * @return string + */ +function apbct_settings__sanitize__excluded_contact_strings($exclusions) +{ + if ( ! is_string($exclusions) ) { + return ''; + } + + $parts = \Cleantalk\Common\ContactsEncoder\Exclusions\ExclusionsService::parseExcludedStrings($exclusions); + $parts = array_slice($parts, 0, 20); + $result = array(); + foreach ( $parts as $part ) { + $part = trim(substr($part, 0, 128), " \n\r\t\v\x00"); + if ( $part !== '' ) { + $result[] = $part; + } + } + + return implode("\n", array_values(array_unique($result))); +} + function apbct_settings__get__long_description() { global $apbct; @@ -3384,6 +3476,10 @@ function apbct_settings__get_long_descriptions_data() 'title' => __('Contact data encoding: phone numbers', 'cleantalk-spam-protect'), 'desc' => ContactsEncoder::getPhonesEncodingLongDescription(), ), + 'data__email_decoder_excluded_strings' => array( + 'title' => __('Contact data encoding: do not encode these contacts', 'cleantalk-spam-protect'), + 'desc' => ContactsEncoder::getExcludedStringsLongDescription(), + ), 'data__email_decoder' => array( 'title' => __('Contact data encoding', 'cleantalk-spam-protect'), 'desc' => ContactsEncoder::getEmailEncoderCommonLongDescription(), diff --git a/inc/cleantalk-wpcli.php b/inc/cleantalk-wpcli.php index b5336e3cc..d232f4138 100755 --- a/inc/cleantalk-wpcli.php +++ b/inc/cleantalk-wpcli.php @@ -108,8 +108,8 @@ public function create($args, $params) } if (isset($result['data']) && !empty($result['data']['auth_key']) && apbct_api_key__is_correct($result['data']['auth_key'])) { - $apbct->data['key_changed'] = trim($result['data']['auth_key']) !== $apbct->settings['apikey']; - $apbct->settings['apikey'] = trim($result['data']['auth_key']); + $apbct->data['key_changed'] = trim($result['data']['auth_key'], " \n\r\t\v\x00") !== $apbct->settings['apikey']; + $apbct->settings['apikey'] = trim($result['data']['auth_key'], " \n\r\t\v\x00"); $apbct->api_key = $apbct->settings['apikey']; $this->prompt(__('Api key installed: ', 'cleantalk-spam-protect') . $apbct->settings['apikey']); } diff --git a/js/apbct-public-bundle.min.js b/js/apbct-public-bundle.min.js index c52849015..a75211562 100644 --- a/js/apbct-public-bundle.min.js +++ b/js/apbct-public-bundle.min.js @@ -1 +1 @@ -function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(i.data.forEach(function(e){e.encoded_email===r[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===r[t].href||0!==r[t].href.indexOf("mailto:")&&0!==r[t].href.indexOf("tel:"))r[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r[t])},2e3);else{if(0===r[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==r[t].href.indexOf("tel:"))return 0;e="tel:"}var o=r[t].href.replace(e,""),a=r[t].innerHTML;r[t].innerHTML=a.replace(o,n.decoded_email),r[t].href=e+n.decoded_email,r[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";i.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}r[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=i.data[0];r.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r)},2e3),r.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(r.innerHTML="Loading...",t&&this.load(t)),r.setAttribute("id","cleantalk-modal-content"),n.append(r),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function u(){_classCallCheck(this,u)}return _createClass(u,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(r),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,i(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),r=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=c(t),f=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,f=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),c=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,r,i,c,l,s,u=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=u.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,m.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,m.apply(this,n));case 3:return e.n=4,_.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=p(n[1].body,d(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,r=t.querySelector('[name*="apbct__email_id__"]'),i=null,c=(null!==r&&null!==r.value&&(i=r.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===c&&null===r&&null===l||(e.preventDefault(),n=function(){null!==r&&r.parentNode.removeChild(r),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=c,null!==i&&(o.apbct_search_form__honeypot_value=i),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,r=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var r=o.value,i=this.findParentContainer(r);if(i){var c=this.getIdFromHTML(i);if(c===n){var l=i.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,r,i,c,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(c=document.createElement("strong")).append(d.phrases.trpHeading),(r=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(i=document.createElement("div")).append(" "),i.append(c),i.append(d.phrases.trpContent1),(c=document.createElement("div")).style.display="flex",c.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),c.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),c.append(l)),r.append(i,c),a.append(r),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file +function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(i.data.forEach(function(e){e.encoded_email===r[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===r[t].href||0!==r[t].href.indexOf("mailto:")&&0!==r[t].href.indexOf("tel:"))r[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r[t])},2e3);else{if(0===r[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==r[t].href.indexOf("tel:"))return 0;e="tel:"}var o=r[t].href.replace(e,""),a=r[t].innerHTML;r[t].innerHTML=a.replace(o,n.decoded_email),r[t].href=e+n.decoded_email,r[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";i.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}r[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=i.data[0];r.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r)},2e3),r.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(r.innerHTML="Loading...",t&&this.load(t)),r.setAttribute("id","cleantalk-modal-content"),n.append(r),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function p(){_classCallCheck(this,p)}return _createClass(p,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(r),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,i(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),r=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=c(t),b=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,b=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),c=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,r,i,c,l,s,u,d,p=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=p.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,h.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,h.apply(this,n));case 3:return e.n=4,m.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=_(n[1].body,f(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,r=t.querySelector('[name*="apbct__email_id__"]'),i=null,c=(null!==r&&null!==r.value&&(i=r.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===c&&null===r&&null===l||(e.preventDefault(),n=function(){null!==r&&r.parentNode.removeChild(r),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=c,null!==i&&(o.apbct_search_form__honeypot_value=i),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,r=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var r=o.value,i=this.findParentContainer(r);if(i){var c=this.getIdFromHTML(i);if(c===n){var l=i.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t{function o(){_classCallCheck(this,o)}return _createClass(o,null,[{key:"getFrontendDataLog",value:function(){var e=("undefined"!=typeof ctPublicFunctions&&ctPublicFunctions.cookiePrefix?ctPublicFunctions.cookiePrefix:"")+o.LOG_KEY,t=o.LOG_KEY;if(void 0!==apbctLocalStorage&&apbctLocalStorage.get){var n=apbctLocalStorage.get(e)||apbctLocalStorage.get(t)||null;if(n&&"string"==typeof n)try{return JSON.parse(n)}catch(e){return""}return n}n=(n=localStorage.getItem(e))||localStorage.getItem(t)||null;try{return"string"==typeof n?JSON.parse(n):n}catch(e){return""}}},{key:"asDTO",value:function(){return{botd_logic_loaded:o.botdLogicLoaded,botd_wrapper_loaded:o.botdWrapperLoaded,frontend_data_log:"",transport_enabled:1}}},{key:"detectScripts",value:function(){if(o.botdWrapperLoaded&&o.botdLogicLoaded)return!0;for(var e=document.getElementsByTagName("script"),t=0;t .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,r,i,c,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(c=document.createElement("strong")).append(d.phrases.trpHeading),(r=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(i=document.createElement("div")).append(" "),i.append(c),i.append(d.phrases.trpContent1),(c=document.createElement("div")).style.display="flex",c.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),c.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),c.append(l)),r.append(i,c),a.append(r),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file diff --git a/js/apbct-public-bundle_ext-protection.min.js b/js/apbct-public-bundle_ext-protection.min.js index 930918ecb..2495d0f51 100644 --- a/js/apbct-public-bundle_ext-protection.min.js +++ b/js/apbct-public-bundle_ext-protection.min.js @@ -1 +1 @@ -function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(c.data.forEach(function(e){e.encoded_email===r[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===r[t].href||0!==r[t].href.indexOf("mailto:")&&0!==r[t].href.indexOf("tel:"))r[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r[t])},2e3);else{if(0===r[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==r[t].href.indexOf("tel:"))return 0;e="tel:"}var o=r[t].href.replace(e,""),a=r[t].innerHTML;r[t].innerHTML=a.replace(o,n.decoded_email),r[t].href=e+n.decoded_email,r[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";c.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}r[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=c.data[0];r.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r)},2e3),r.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(r.innerHTML="Loading...",t&&this.load(t)),r.setAttribute("id","cleantalk-modal-content"),n.append(r),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function u(){_classCallCheck(this,u)}return _createClass(u,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(r),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,c(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),r=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=i(t),m=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,m=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),i=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,r,c,i,l,s,u=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=u.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,_.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,_.apply(this,n));case 3:return e.n=4,f.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=p(n[1].body,d(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,r=t.querySelector('[name*="apbct__email_id__"]'),c=null,i=(null!==r&&null!==r.value&&(c=r.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===i&&null===r&&null===l||(e.preventDefault(),n=function(){null!==r&&r.parentNode.removeChild(r),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=i,null!==c&&(o.apbct_search_form__honeypot_value=c),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,r=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var r=o.value,c=this.findParentContainer(r);if(c){var i=this.getIdFromHTML(c);if(i===n){var l=c.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,r,c,i,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(i=document.createElement("strong")).append(d.phrases.trpHeading),(r=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(c=document.createElement("div")).append(" "),c.append(i),c.append(d.phrases.trpContent1),(i=document.createElement("div")).style.display="flex",i.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),i.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),i.append(l)),r.append(c,i),a.append(r),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file +function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(i.data.forEach(function(e){e.encoded_email===r[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===r[t].href||0!==r[t].href.indexOf("mailto:")&&0!==r[t].href.indexOf("tel:"))r[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r[t])},2e3);else{if(0===r[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==r[t].href.indexOf("tel:"))return 0;e="tel:"}var o=r[t].href.replace(e,""),a=r[t].innerHTML;r[t].innerHTML=a.replace(o,n.decoded_email),r[t].href=e+n.decoded_email,r[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";i.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}r[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=i.data[0];r.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r)},2e3),r.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(r.innerHTML="Loading...",t&&this.load(t)),r.setAttribute("id","cleantalk-modal-content"),n.append(r),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function p(){_classCallCheck(this,p)}return _createClass(p,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(r),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,i(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),r=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=c(t),b=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,b=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),c=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,r,i,c,l,s,u,d,p=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=p.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,h.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,h.apply(this,n));case 3:return e.n=4,_.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=m(n[1].body,f(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,r=t.querySelector('[name*="apbct__email_id__"]'),i=null,c=(null!==r&&null!==r.value&&(i=r.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===c&&null===r&&null===l||(e.preventDefault(),n=function(){null!==r&&r.parentNode.removeChild(r),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=c,null!==i&&(o.apbct_search_form__honeypot_value=i),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,r=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var r=o.value,i=this.findParentContainer(r);if(i){var c=this.getIdFromHTML(i);if(c===n){var l=i.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t{function o(){_classCallCheck(this,o)}return _createClass(o,null,[{key:"getFrontendDataLog",value:function(){var e=("undefined"!=typeof ctPublicFunctions&&ctPublicFunctions.cookiePrefix?ctPublicFunctions.cookiePrefix:"")+o.LOG_KEY,t=o.LOG_KEY;if(void 0!==apbctLocalStorage&&apbctLocalStorage.get){var n=apbctLocalStorage.get(e)||apbctLocalStorage.get(t)||null;if(n&&"string"==typeof n)try{return JSON.parse(n)}catch(e){return""}return n}n=(n=localStorage.getItem(e))||localStorage.getItem(t)||null;try{return"string"==typeof n?JSON.parse(n):n}catch(e){return""}}},{key:"asDTO",value:function(){return{botd_logic_loaded:o.botdLogicLoaded,botd_wrapper_loaded:o.botdWrapperLoaded,frontend_data_log:"",transport_enabled:1}}},{key:"detectScripts",value:function(){if(o.botdWrapperLoaded&&o.botdLogicLoaded)return!0;for(var e=document.getElementsByTagName("script"),t=0;t .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,r,i,c,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(c=document.createElement("strong")).append(d.phrases.trpHeading),(r=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(i=document.createElement("div")).append(" "),i.append(c),i.append(d.phrases.trpContent1),(c=document.createElement("div")).style.display="flex",c.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),c.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),c.append(l)),r.append(i,c),a.append(r),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file diff --git a/js/apbct-public-bundle_ext-protection_gathering.min.js b/js/apbct-public-bundle_ext-protection_gathering.min.js index 00eb9cbd0..c7c09ae4e 100644 --- a/js/apbct-public-bundle_ext-protection_gathering.min.js +++ b/js/apbct-public-bundle_ext-protection_gathering.min.js @@ -1 +1 @@ -function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||c=e.length?{done:!0}:{done:!1,value:e[c++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(i.data.forEach(function(e){e.encoded_email===c[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===c[t].href||0!==c[t].href.indexOf("mailto:")&&0!==c[t].href.indexOf("tel:"))c[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,c[t])},2e3);else{if(0===c[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==c[t].href.indexOf("tel:"))return 0;e="tel:"}var o=c[t].href.replace(e,""),a=c[t].innerHTML;c[t].innerHTML=a.replace(o,n.decoded_email),c[t].href=e+n.decoded_email,c[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";i.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}c[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=i.data[0];c.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,c)},2e3),c.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(c.innerHTML="Loading...",t&&this.load(t)),c.setAttribute("id","cleantalk-modal-content"),n.append(c),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function u(){_classCallCheck(this,u)}return _createClass(u,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(c),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,i(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),c=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=r(t),f=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,f=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),r=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,c,i,r,l,s,u=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=u.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,m.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,m.apply(this,n));case 3:return e.n=4,_.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=p(n[1].body,d(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,c=t.querySelector('[name*="apbct__email_id__"]'),i=null,r=(null!==c&&null!==c.value&&(i=c.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===r&&null===c&&null===l||(e.preventDefault(),n=function(){null!==c&&c.parentNode.removeChild(c),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=r,null!==i&&(o.apbct_search_form__honeypot_value=i),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,c=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var c=o.value,i=this.findParentContainer(c);if(i){var r=this.getIdFromHTML(i);if(r===n){var l=i.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t_createClass(function e(){_classCallCheck(this,e)},[{key:"setSessionId",value:function(){var e;apbctSessionStorage.isSet("apbct_session_id")?apbctLocalStorage.set("apbct_page_hits",Number(apbctLocalStorage.get("apbct_page_hits"))+1):(e=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(2,10),apbctSessionStorage.set("apbct_session_id",e,!1),apbctLocalStorage.set("apbct_page_hits",1),document.referrer&&new URL(document.referrer).host!==location.host&&apbctSessionStorage.set("apbct_site_referer",document.referrer,!1))}},{key:"writeReferrersToSessionStorage",value:function(){var e=apbctSessionStorage.get("apbct_session_current_page");!1!==e&&document.location.href!==e&&apbctSessionStorage.set("apbct_prev_referer",e,!1),apbctSessionStorage.set("apbct_session_current_page",document.location.href,!1)}},{key:"setCookiesType",value:function(){var e=apbctLocalStorage.get("ct_cookies_type");e&&e===ctPublic.data__cookies_type||(apbctLocalStorage.set("ct_cookies_type",ctPublic.data__cookies_type),apbctLocalStorage.delete("ct_mouse_moved"),apbctLocalStorage.delete("ct_has_scrolled"))}},{key:"startFieldsListening",value:function(){if(!apbctLocalStorage.isSet("ct_has_key_up")&&!apbctLocalStorage.get("ct_has_key_up")||!apbctLocalStorage.isSet("ct_has_input_focused")&&!apbctLocalStorage.get("ct_has_input_focused")||"native"!==ctPublic.data__cookies_type||void 0===ctGetCookie("ct_has_input_focused")||void 0===ctGetCookie("ct_has_key_up")){var e=ctGetPageForms();if(ctPublic.handled_fields=[],0_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"elementBody",document.querySelector("body")),_defineProperty(this,"collectionForms",document.forms),this.setListeners()},[{key:"setListeners",value:function(){var t=this;this.elementBody.addEventListener("click",function(e){t.checkElementInForms(e,"addClicks")}),this.elementBody.addEventListener("mouseup",function(e){"Range"==document.getSelection().type.toString()&&t.addSelected()}),this.elementBody.addEventListener("mousemove",function(e){t.checkElementInForms(e,"trackMouseMovement")})}},{key:"checkElementInForms",value:function(e,t){for(var n,o=0;o_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"fieldData",{isAutoFill:!1,isUseBuffer:!1,speedDelta:0,firstKeyTimestamp:0,lastKeyTimestamp:0,lastDelta:0,countOfKey:0}),_defineProperty(this,"fields",document.querySelectorAll("textarea[name=comment]")),_defineProperty(this,"data",[])},[{key:"gatheringFields",value:function(){var n=this;Array.prototype.slice.call(this.fields).forEach(function(e,t){n.data.push(Object.assign({},n.fieldData))})}},{key:"setListeners",value:function(){var o=this;this.fields.forEach(function(e,t){e.addEventListener("paste",function(){o.data[t].isUseBuffer=!0})}),this.fields.forEach(function(e,t){e.addEventListener("onautocomplete",function(){o.data[t].isAutoFill=!0})}),this.fields.forEach(function(e,n){e.addEventListener("input",function(){o.data[n].countOfKey++;var e,t=+new Date;1===o.data[n].countOfKey?(o.data[n].lastKeyTimestamp=t,o.data[n].firstKeyTimestamp=t):(e=t-o.data[n].lastKeyTimestamp,2===o.data[n].countOfKey?(o.data[n].lastKeyTimestamp=t,o.data[n].lastDelta=e):2 .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,c,i,r,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(r=document.createElement("strong")).append(d.phrases.trpHeading),(c=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(i=document.createElement("div")).append(" "),i.append(r),i.append(d.phrases.trpContent1),(r=document.createElement("div")).style.display="flex",r.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),r.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),r.append(l)),c.append(i,r),a.append(c),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file +function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||c=e.length?{done:!0}:{done:!1,value:e[c++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(r.data.forEach(function(e){e.encoded_email===c[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===c[t].href||0!==c[t].href.indexOf("mailto:")&&0!==c[t].href.indexOf("tel:"))c[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,c[t])},2e3);else{if(0===c[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==c[t].href.indexOf("tel:"))return 0;e="tel:"}var o=c[t].href.replace(e,""),a=c[t].innerHTML;c[t].innerHTML=a.replace(o,n.decoded_email),c[t].href=e+n.decoded_email,c[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";r.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}c[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=r.data[0];c.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,c)},2e3),c.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(c.innerHTML="Loading...",t&&this.load(t)),c.setAttribute("id","cleantalk-modal-content"),n.append(c),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function p(){_classCallCheck(this,p)}return _createClass(p,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(c),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,r(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),c=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=i(t),b=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,b=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),i=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,c,r,i,l,s,u,d,p=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=p.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,h.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,h.apply(this,n));case 3:return e.n=4,m.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=_(n[1].body,f(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,c=t.querySelector('[name*="apbct__email_id__"]'),r=null,i=(null!==c&&null!==c.value&&(r=c.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===i&&null===c&&null===l||(e.preventDefault(),n=function(){null!==c&&c.parentNode.removeChild(c),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=i,null!==r&&(o.apbct_search_form__honeypot_value=r),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,c=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var c=o.value,r=this.findParentContainer(c);if(r){var i=this.getIdFromHTML(r);if(i===n){var l=r.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t_createClass(function e(){_classCallCheck(this,e)},[{key:"setSessionId",value:function(){var e;apbctSessionStorage.isSet("apbct_session_id")?apbctLocalStorage.set("apbct_page_hits",Number(apbctLocalStorage.get("apbct_page_hits"))+1):(e=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(2,10),apbctSessionStorage.set("apbct_session_id",e,!1),apbctLocalStorage.set("apbct_page_hits",1),document.referrer&&new URL(document.referrer).host!==location.host&&apbctSessionStorage.set("apbct_site_referer",document.referrer,!1))}},{key:"writeReferrersToSessionStorage",value:function(){var e=apbctSessionStorage.get("apbct_session_current_page");!1!==e&&document.location.href!==e&&apbctSessionStorage.set("apbct_prev_referer",e,!1),apbctSessionStorage.set("apbct_session_current_page",document.location.href,!1)}},{key:"setCookiesType",value:function(){var e=apbctLocalStorage.get("ct_cookies_type");e&&e===ctPublic.data__cookies_type||(apbctLocalStorage.set("ct_cookies_type",ctPublic.data__cookies_type),apbctLocalStorage.delete("ct_mouse_moved"),apbctLocalStorage.delete("ct_has_scrolled"))}},{key:"startFieldsListening",value:function(){if(!apbctLocalStorage.isSet("ct_has_key_up")&&!apbctLocalStorage.get("ct_has_key_up")||!apbctLocalStorage.isSet("ct_has_input_focused")&&!apbctLocalStorage.get("ct_has_input_focused")||"native"!==ctPublic.data__cookies_type||void 0===ctGetCookie("ct_has_input_focused")||void 0===ctGetCookie("ct_has_key_up")){var e=ctGetPageForms();if(ctPublic.handled_fields=[],0_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"elementBody",document.querySelector("body")),_defineProperty(this,"collectionForms",document.forms),this.setListeners()},[{key:"setListeners",value:function(){var t=this;this.elementBody.addEventListener("click",function(e){t.checkElementInForms(e,"addClicks")}),this.elementBody.addEventListener("mouseup",function(e){"Range"==document.getSelection().type.toString()&&t.addSelected()}),this.elementBody.addEventListener("mousemove",function(e){t.checkElementInForms(e,"trackMouseMovement")})}},{key:"checkElementInForms",value:function(e,t){for(var n,o=0;o_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"fieldData",{isAutoFill:!1,isUseBuffer:!1,speedDelta:0,firstKeyTimestamp:0,lastKeyTimestamp:0,lastDelta:0,countOfKey:0}),_defineProperty(this,"fields",document.querySelectorAll("textarea[name=comment]")),_defineProperty(this,"data",[])},[{key:"gatheringFields",value:function(){var n=this;Array.prototype.slice.call(this.fields).forEach(function(e,t){n.data.push(Object.assign({},n.fieldData))})}},{key:"setListeners",value:function(){var o=this;this.fields.forEach(function(e,t){e.addEventListener("paste",function(){o.data[t].isUseBuffer=!0})}),this.fields.forEach(function(e,t){e.addEventListener("onautocomplete",function(){o.data[t].isAutoFill=!0})}),this.fields.forEach(function(e,n){e.addEventListener("input",function(){o.data[n].countOfKey++;var e,t=+new Date;1===o.data[n].countOfKey?(o.data[n].lastKeyTimestamp=t,o.data[n].firstKeyTimestamp=t):(e=t-o.data[n].lastKeyTimestamp,2===o.data[n].countOfKey?(o.data[n].lastKeyTimestamp=t,o.data[n].lastDelta=e):2{function o(){_classCallCheck(this,o)}return _createClass(o,null,[{key:"getFrontendDataLog",value:function(){var e=("undefined"!=typeof ctPublicFunctions&&ctPublicFunctions.cookiePrefix?ctPublicFunctions.cookiePrefix:"")+o.LOG_KEY,t=o.LOG_KEY;if(void 0!==apbctLocalStorage&&apbctLocalStorage.get){var n=apbctLocalStorage.get(e)||apbctLocalStorage.get(t)||null;if(n&&"string"==typeof n)try{return JSON.parse(n)}catch(e){return""}return n}n=(n=localStorage.getItem(e))||localStorage.getItem(t)||null;try{return"string"==typeof n?JSON.parse(n):n}catch(e){return""}}},{key:"asDTO",value:function(){return{botd_logic_loaded:o.botdLogicLoaded,botd_wrapper_loaded:o.botdWrapperLoaded,frontend_data_log:"",transport_enabled:1}}},{key:"detectScripts",value:function(){if(o.botdWrapperLoaded&&o.botdLogicLoaded)return!0;for(var e=document.getElementsByTagName("script"),t=0;t .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,c,r,i,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(i=document.createElement("strong")).append(d.phrases.trpHeading),(c=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(r=document.createElement("div")).append(" "),r.append(i),r.append(d.phrases.trpContent1),(i=document.createElement("div")).style.display="flex",i.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),i.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),i.append(l)),c.append(r,i),a.append(c),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file diff --git a/js/apbct-public-bundle_full-protection.min.js b/js/apbct-public-bundle_full-protection.min.js index 512e4ca15..0a443cba6 100644 --- a/js/apbct-public-bundle_full-protection.min.js +++ b/js/apbct-public-bundle_full-protection.min.js @@ -1 +1 @@ -function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(c.data.forEach(function(e){e.encoded_email===r[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===r[t].href||0!==r[t].href.indexOf("mailto:")&&0!==r[t].href.indexOf("tel:"))r[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r[t])},2e3);else{if(0===r[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==r[t].href.indexOf("tel:"))return 0;e="tel:"}var o=r[t].href.replace(e,""),a=r[t].innerHTML;r[t].innerHTML=a.replace(o,n.decoded_email),r[t].href=e+n.decoded_email,r[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";c.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}r[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=c.data[0];r.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r)},2e3),r.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(r.innerHTML="Loading...",t&&this.load(t)),r.setAttribute("id","cleantalk-modal-content"),n.append(r),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function u(){_classCallCheck(this,u)}return _createClass(u,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(r),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,c(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),r=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=i(t),m=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,m=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),i=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,r,c,i,l,s,u=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=u.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,_.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,_.apply(this,n));case 3:return e.n=4,f.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=p(n[1].body,d(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,r=t.querySelector('[name*="apbct__email_id__"]'),c=null,i=(null!==r&&null!==r.value&&(c=r.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===i&&null===r&&null===l||(e.preventDefault(),n=function(){null!==r&&r.parentNode.removeChild(r),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=i,null!==c&&(o.apbct_search_form__honeypot_value=c),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,r=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var r=o.value,c=this.findParentContainer(r);if(c){var i=this.getIdFromHTML(c);if(i===n){var l=c.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"wrappers",[]),this.wrappers=this.findWrappers(),this.wrappers.length<1||this.checkBot()},[{key:"findWrappers",value:function(){return document.querySelectorAll("div.ct-encoded-form-wrapper")}},{key:"checkBot",value:function(){var t=this,e={post_url:document.location.href,referrer:document.referrer};+ctPublic.bot_detector_enabled?e.event_token=apbctLocalStorage.get("bot_detector_event_token"):e.event_javascript_data=getJavascriptClientData(),"rest"===ctPublicFunctions.data__ajax_type?apbct_public_sendREST("force_protection_check_bot",{data:e,method:"POST",callback:function(e){return t.checkBotCallback(e)}}):"admin_ajax"===ctPublicFunctions.data__ajax_type&&(e.action="apbct_force_protection_check_bot",apbct_public_sendAJAX(e,{callback:function(e){return t.checkBotCallback(e)}}))}},{key:"checkBotCallback",value:function(e){if(e.data&&e.data.status&&200!==e.data.status)console.log("ApbctForceProtection connection error occurred"),this.decodeForms();else{if("string"==typeof e)try{e=JSON.parse(e)}catch(e){return console.log("ApbctForceProtection decodeForms error",e),void this.decodeForms()}"object"===_typeof(e)&&e.allow&&1===e.allow?(this.decodeForms(),document.dispatchEvent(new Event("apbctForceProtectionAllowed"))):this.showMessageForBot(e.message)}}},{key:"decodeForms",value:function(){var n;this.wrappers.forEach(function(e){n=e.querySelector("div.ct-encoded-form").dataset.encodedForm;try{var t;n&&"string"==typeof n&&(t=decodeURIComponent(n),e.outerHTML=atob(t))}catch(e){console.log(e)}})}},{key:"showMessageForBot",value:function(t){this.wrappers.forEach(function(e){e.querySelector("div.ct-encoded-form").dataset.encodedForm&&(e.outerHTML='
'+t+"
")})}}]))();function apbctForceProtect(){+ctPublic.settings__forms__force_protection&&void 0!==ApbctForceProtection&&new ApbctForceProtection}function ctCheckInternal(t){var e,n={},o=t.elements;for(e in o)"submit"!==o[e].type&&void 0!==o[e].value&&""!==o[e].value&&(n[o[e].name]=t.elements[e].value);n.action="ct_check_internal",apbct_public_sendAJAX(n,{url:ctPublicFunctions._ajax_url,callback:function(e){if(!0!==e.success)return alert(e.data),!1;t.origSubmit()}})}function ctProtectInternalForms(){for(var e,t="",n="",o=0;o .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,r,c,i,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(i=document.createElement("strong")).append(d.phrases.trpHeading),(r=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(c=document.createElement("div")).append(" "),c.append(i),c.append(d.phrases.trpContent1),(i=document.createElement("div")).style.display="flex",i.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),i.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),i.append(l)),r.append(c,i),a.append(r),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file +function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(c.data.forEach(function(e){e.encoded_email===r[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===r[t].href||0!==r[t].href.indexOf("mailto:")&&0!==r[t].href.indexOf("tel:"))r[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r[t])},2e3);else{if(0===r[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==r[t].href.indexOf("tel:"))return 0;e="tel:"}var o=r[t].href.replace(e,""),a=r[t].innerHTML;r[t].innerHTML=a.replace(o,n.decoded_email),r[t].href=e+n.decoded_email,r[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";c.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}r[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=c.data[0];r.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r)},2e3),r.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(r.innerHTML="Loading...",t&&this.load(t)),r.setAttribute("id","cleantalk-modal-content"),n.append(r),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function p(){_classCallCheck(this,p)}return _createClass(p,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(r),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,c(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),r=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=i(t),b=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,b=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),i=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,r,c,i,l,s,u,d,p=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=p.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,h.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,h.apply(this,n));case 3:return e.n=4,_.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=m(n[1].body,f(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,r=t.querySelector('[name*="apbct__email_id__"]'),c=null,i=(null!==r&&null!==r.value&&(c=r.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===i&&null===r&&null===l||(e.preventDefault(),n=function(){null!==r&&r.parentNode.removeChild(r),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=i,null!==c&&(o.apbct_search_form__honeypot_value=c),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,r=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var r=o.value,c=this.findParentContainer(r);if(c){var i=this.getIdFromHTML(c);if(i===n){var l=c.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"wrappers",[]),this.wrappers=this.findWrappers(),this.wrappers.length<1||this.checkBot()},[{key:"findWrappers",value:function(){return document.querySelectorAll("div.ct-encoded-form-wrapper")}},{key:"checkBot",value:function(){var t=this,e={post_url:document.location.href,referrer:document.referrer};+ctPublic.bot_detector_enabled?e.event_token=apbctLocalStorage.get("bot_detector_event_token"):e.event_javascript_data=getJavascriptClientData(),"rest"===ctPublicFunctions.data__ajax_type?apbct_public_sendREST("force_protection_check_bot",{data:e,method:"POST",callback:function(e){return t.checkBotCallback(e)}}):"admin_ajax"===ctPublicFunctions.data__ajax_type&&(e.action="apbct_force_protection_check_bot",apbct_public_sendAJAX(e,{callback:function(e){return t.checkBotCallback(e)}}))}},{key:"checkBotCallback",value:function(e){if(e.data&&e.data.status&&200!==e.data.status)console.log("ApbctForceProtection connection error occurred"),this.decodeForms();else{if("string"==typeof e)try{e=JSON.parse(e)}catch(e){return console.log("ApbctForceProtection decodeForms error",e),void this.decodeForms()}"object"===_typeof(e)&&e.allow&&1===e.allow?(this.decodeForms(),document.dispatchEvent(new Event("apbctForceProtectionAllowed"))):this.showMessageForBot(e.message)}}},{key:"decodeForms",value:function(){var n;this.wrappers.forEach(function(e){n=e.querySelector("div.ct-encoded-form").dataset.encodedForm;try{var t;n&&"string"==typeof n&&(t=decodeURIComponent(n),e.outerHTML=atob(t))}catch(e){console.log(e)}})}},{key:"showMessageForBot",value:function(t){this.wrappers.forEach(function(e){e.querySelector("div.ct-encoded-form").dataset.encodedForm&&(e.outerHTML='
'+t+"
")})}}]))();function apbctForceProtect(){+ctPublic.settings__forms__force_protection&&void 0!==ApbctForceProtection&&new ApbctForceProtection}function ctCheckInternal(t){var e,n={},o=t.elements;for(e in o)"submit"!==o[e].type&&void 0!==o[e].value&&""!==o[e].value&&(n[o[e].name]=t.elements[e].value);n.action="ct_check_internal",apbct_public_sendAJAX(n,{url:ctPublicFunctions._ajax_url,callback:function(e){if(!0!==e.success)return alert(e.data),!1;t.origSubmit()}})}function ctProtectInternalForms(){for(var e,t="",n="",o=0;o{function o(){_classCallCheck(this,o)}return _createClass(o,null,[{key:"getFrontendDataLog",value:function(){var e=("undefined"!=typeof ctPublicFunctions&&ctPublicFunctions.cookiePrefix?ctPublicFunctions.cookiePrefix:"")+o.LOG_KEY,t=o.LOG_KEY;if(void 0!==apbctLocalStorage&&apbctLocalStorage.get){var n=apbctLocalStorage.get(e)||apbctLocalStorage.get(t)||null;if(n&&"string"==typeof n)try{return JSON.parse(n)}catch(e){return""}return n}n=(n=localStorage.getItem(e))||localStorage.getItem(t)||null;try{return"string"==typeof n?JSON.parse(n):n}catch(e){return""}}},{key:"asDTO",value:function(){return{botd_logic_loaded:o.botdLogicLoaded,botd_wrapper_loaded:o.botdWrapperLoaded,frontend_data_log:"",transport_enabled:1}}},{key:"detectScripts",value:function(){if(o.botdWrapperLoaded&&o.botdLogicLoaded)return!0;for(var e=document.getElementsByTagName("script"),t=0;t .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,r,c,i,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(i=document.createElement("strong")).append(d.phrases.trpHeading),(r=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(c=document.createElement("div")).append(" "),c.append(i),c.append(d.phrases.trpContent1),(i=document.createElement("div")).style.display="flex",i.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),i.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),i.append(l)),r.append(c,i),a.append(r),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file diff --git a/js/apbct-public-bundle_full-protection_gathering.min.js b/js/apbct-public-bundle_full-protection_gathering.min.js index 4ec656f2d..0fc9cc71f 100644 --- a/js/apbct-public-bundle_full-protection_gathering.min.js +++ b/js/apbct-public-bundle_full-protection_gathering.min.js @@ -1 +1 @@ -function ownKeys(t,e){var o,n=Object.keys(t);return Object.getOwnPropertySymbols&&(o=Object.getOwnPropertySymbols(t),e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)),n}function _objectSpread(t){for(var e=1;et||c=e.length?{done:!0}:{done:!1,value:e[c++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var o;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(o="Object"===(o={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:o)||"Set"===o?Array.from(e):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var o=0,n=Array(t);o{var o,e;if(i.data.forEach(function(e){e.encoded_email===c[t].dataset.originalString&&(o=e)}),!1===o.is_allowed)return{v:void 0};if(void 0===c[t].href||0!==c[t].href.indexOf("mailto:")&&0!==c[t].href.indexOf("tel:"))c[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(o,c[t])},2e3);else{if(0===c[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==c[t].href.indexOf("tel:"))return 0;e="tel:"}var n=c[t].href.replace(e,""),a=c[t].innerHTML;c[t].innerHTML=a.replace(n,o.decoded_email),c[t].href=e+o.decoded_email,c[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var o="";i.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(o=e.decoded_email)}),t.innerHTML=o})}c[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var o=i.data[0];c.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(o,c)},2e3),c.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(c.innerHTML="Loading...",t&&this.load(t)),c.setAttribute("id","cleantalk-modal-content"),o.append(c),this.opened=!0},confirm:function(e){var t,o=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var o in e)if(Object.hasOwn(e,o))for(var n=o.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?o||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?o||Boolean(e[t]):o||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):o}},{key:"isWithoutSelector",value:function(e,t){var o,n=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(o=a.n()).done;)n=n||e===o.value}catch(e){a.e(e)}finally{a.f()}return n}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,o=_createForOfIteratorHelper(this.elements);try{for(o.s();!(t=o.n()).done;)t.value.after(e)}catch(e){o.e(e)}finally{o.f()}}},{key:"append",value:function(e){var t,o=_createForOfIteratorHelper(this.elements);try{for(o.s();!(t=o.n()).done;)t.value.append(e)}catch(e){o.e(e)}finally{o.f()}}},{key:"fadeIn",value:function(n){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-o)/n,o=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,o=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(n){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-o)/n,o=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,o=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function n(e){for(var t in _classCallCheck(this,n),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(n,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,o="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(o=e.headers["X-WP-Nonce"]),""!==(o=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:o)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:o,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),o=0;o{function n(){for(var e=arguments.length,t=new Array(e),o=0;o{function a(){for(var e=arguments.length,t=new Array(e),o=0;o{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",o=0,n=Object.entries(this.config);oMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(n){n.addEventListener("click",function(e){var t=n.getAttribute("href"),o=apbctLocalStorage.get("bot_detector_event_token");o&&(-1===t.indexOf("?")?t+="?":t+="&",n.setAttribute("href",t+="ct_bot_detector_event_token="+o))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var o=document.createElement("input"),t=(o.setAttribute("type","hidden"),o.setAttribute("id","apbct_visible_fields_"+t),o.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),o.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(o)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),o=getCleanTalkStorageDataArray(),o=JSON.stringify(o);return o="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(o))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",o),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,o;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(o="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,o+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(o="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,o+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var o="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var n in o){if(10{function u(){_classCallCheck(this,u)}return _createClass(u,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var o=_asyncToGenerator(_regenerator().m(function e(t,o){var n,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:n=_createForOfIteratorHelper(c),e.p=2,n.s();case 3:if((a=n.n()).done)e.n=6;else{if((a=a.value).matches(t,o))return a=a.getForm(),e.n=4,i(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,n.e(a);case 8:return e.p=8,n.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return o.apply(this,arguments)}})(),c=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var o,n,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return o=r(t),f=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(o,{async:!0,callback:e,onErrorCallback:t})});case 3:return n=e.v,(a=void 0!==n.apbct&&+n.apbct.blocked||void 0!==n.data&&void 0!==n.data.message)&&(new ApbctShowForbidden).parseBlockMessage(n),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,f=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),r=function(e){var t,o={action:"cleantalk_force_ajax_check"},n=_createForOfIteratorHelper(e.elements);try{for(n.s();!(t=n.n()).done;){var a=t.value;a.name&&(o[a.name]=a.value)}}catch(e){n.e(e)}finally{n.f()}return+ctPublic.bot_detector_enabled?o.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):o.ct_no_cookie_hidden_field=getNoCookieData(),o};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,o,n,a,c,i,r,l,s,u=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=u.length,o=new Array(t),n=0;n!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof o[0]?o[0]:(null==(a=o[0])?void 0:a.url)||""))return e.a(2,m.apply(this,o));e.n=2;break;case 2:if(o&&o[0]&&o[1]&&o[1].body){e.n=3;break}return e.a(2,m.apply(this,o));case 3:return e.n=4,_.processFetch(o);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return o[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{o[1].body=p(o[1].body,d(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return o.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var o,n,a,c=t.querySelector('[name*="apbct__email_id__"]'),i=null,r=(null!==c&&null!==c.value&&(i=c.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===r&&null===c&&null===l||(e.preventDefault(),o=function(){null!==c&&c.parentNode.removeChild(c),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},n=r,null!==i&&(n.apbct_search_form__honeypot_value=i),n.ct_bot_detector_event_token=l,"string"==typeof n.apbct_pixel_url&&-1!==n.apbct_pixel_url.indexOf("%3A")&&(n.apbct_pixel_url=decodeURIComponent(n.apbct_pixel_url)),void 0!==(a=JSON.stringify(n))&&0!==a.length?ctSetAlternativeCookie(a,{callback:o,onErrorCallback:o,forceAltCookies:!0}):o())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var n=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,o){n(t)}):jQuery(document).ajaxComplete(function(e,t,o){n(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&n(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,o="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(o=e.comment),o=void 0!==e.data&&void 0!==(e=e.data).message?e.message:o)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:o}})),cleantalkModal.loaded=o,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var n=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&n.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,c=n;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),o=this.getIdFromAjax(e);if(o){var n,a=_createForOfIteratorHelper(t);try{for(a.s();!(n=a.n()).done;){var c=n.value,i=this.findParentContainer(c);if(i){var r=this.getIdFromHTML(i);if(r===o){var l=i.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,o=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,o=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"wrappers",[]),this.wrappers=this.findWrappers(),this.wrappers.length<1||this.checkBot()},[{key:"findWrappers",value:function(){return document.querySelectorAll("div.ct-encoded-form-wrapper")}},{key:"checkBot",value:function(){var t=this,e={post_url:document.location.href,referrer:document.referrer};+ctPublic.bot_detector_enabled?e.event_token=apbctLocalStorage.get("bot_detector_event_token"):e.event_javascript_data=getJavascriptClientData(),"rest"===ctPublicFunctions.data__ajax_type?apbct_public_sendREST("force_protection_check_bot",{data:e,method:"POST",callback:function(e){return t.checkBotCallback(e)}}):"admin_ajax"===ctPublicFunctions.data__ajax_type&&(e.action="apbct_force_protection_check_bot",apbct_public_sendAJAX(e,{callback:function(e){return t.checkBotCallback(e)}}))}},{key:"checkBotCallback",value:function(e){if(e.data&&e.data.status&&200!==e.data.status)console.log("ApbctForceProtection connection error occurred"),this.decodeForms();else{if("string"==typeof e)try{e=JSON.parse(e)}catch(e){return console.log("ApbctForceProtection decodeForms error",e),void this.decodeForms()}"object"===_typeof(e)&&e.allow&&1===e.allow?(this.decodeForms(),document.dispatchEvent(new Event("apbctForceProtectionAllowed"))):this.showMessageForBot(e.message)}}},{key:"decodeForms",value:function(){var o;this.wrappers.forEach(function(e){o=e.querySelector("div.ct-encoded-form").dataset.encodedForm;try{var t;o&&"string"==typeof o&&(t=decodeURIComponent(o),e.outerHTML=atob(t))}catch(e){console.log(e)}})}},{key:"showMessageForBot",value:function(t){this.wrappers.forEach(function(e){e.querySelector("div.ct-encoded-form").dataset.encodedForm&&(e.outerHTML='
'+t+"
")})}}]))();function apbctForceProtect(){+ctPublic.settings__forms__force_protection&&void 0!==ApbctForceProtection&&new ApbctForceProtection}ctPublic.data__key_is_ok&&("loading"!==document.readyState?apbctForceProtect():apbct_attach_event_handler(document,"DOMContentLoaded",apbctForceProtect));var ctMouseReadInterval,ctMouseWriteDataInterval,ApbctGatheringData=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"setSessionId",value:function(){var e;apbctSessionStorage.isSet("apbct_session_id")?apbctLocalStorage.set("apbct_page_hits",Number(apbctLocalStorage.get("apbct_page_hits"))+1):(e=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(2,10),apbctSessionStorage.set("apbct_session_id",e,!1),apbctLocalStorage.set("apbct_page_hits",1),document.referrer&&new URL(document.referrer).host!==location.host&&apbctSessionStorage.set("apbct_site_referer",document.referrer,!1))}},{key:"writeReferrersToSessionStorage",value:function(){var e=apbctSessionStorage.get("apbct_session_current_page");!1!==e&&document.location.href!==e&&apbctSessionStorage.set("apbct_prev_referer",e,!1),apbctSessionStorage.set("apbct_session_current_page",document.location.href,!1)}},{key:"setCookiesType",value:function(){var e=apbctLocalStorage.get("ct_cookies_type");e&&e===ctPublic.data__cookies_type||(apbctLocalStorage.set("ct_cookies_type",ctPublic.data__cookies_type),apbctLocalStorage.delete("ct_mouse_moved"),apbctLocalStorage.delete("ct_has_scrolled"))}},{key:"startFieldsListening",value:function(){if(!apbctLocalStorage.isSet("ct_has_key_up")&&!apbctLocalStorage.get("ct_has_key_up")||!apbctLocalStorage.isSet("ct_has_input_focused")&&!apbctLocalStorage.get("ct_has_input_focused")||"native"!==ctPublic.data__cookies_type||void 0===ctGetCookie("ct_has_input_focused")||void 0===ctGetCookie("ct_has_key_up")){var e=ctGetPageForms();if(ctPublic.handled_fields=[],0_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"elementBody",document.querySelector("body")),_defineProperty(this,"collectionForms",document.forms),this.setListeners()},[{key:"setListeners",value:function(){var t=this;this.elementBody.addEventListener("click",function(e){t.checkElementInForms(e,"addClicks")}),this.elementBody.addEventListener("mouseup",function(e){"Range"==document.getSelection().type.toString()&&t.addSelected()}),this.elementBody.addEventListener("mousemove",function(e){t.checkElementInForms(e,"trackMouseMovement")})}},{key:"checkElementInForms",value:function(e,t){for(var o,n=0;n_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"fieldData",{isAutoFill:!1,isUseBuffer:!1,speedDelta:0,firstKeyTimestamp:0,lastKeyTimestamp:0,lastDelta:0,countOfKey:0}),_defineProperty(this,"fields",document.querySelectorAll("textarea[name=comment]")),_defineProperty(this,"data",[])},[{key:"gatheringFields",value:function(){var o=this;Array.prototype.slice.call(this.fields).forEach(function(e,t){o.data.push(Object.assign({},o.fieldData))})}},{key:"setListeners",value:function(){var n=this;this.fields.forEach(function(e,t){e.addEventListener("paste",function(){n.data[t].isUseBuffer=!0})}),this.fields.forEach(function(e,t){e.addEventListener("onautocomplete",function(){n.data[t].isAutoFill=!0})}),this.fields.forEach(function(e,o){e.addEventListener("input",function(){n.data[o].countOfKey++;var e,t=+new Date;1===n.data[o].countOfKey?(n.data[o].lastKeyTimestamp=t,n.data[o].firstKeyTimestamp=t):(e=t-n.data[o].lastKeyTimestamp,2===n.data[o].countOfKey?(n.data[o].lastKeyTimestamp=t,n.data[o].lastDelta=e):2 .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var o,n,a,c,i,r,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((o=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(n=document.createElement("img")).setAttribute("src",d.imgPersonUrl),n.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(r=document.createElement("strong")).append(d.phrases.trpHeading),(c=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(i=document.createElement("div")).append(" "),i.append(r),i.append(d.phrases.trpContent1),(r=document.createElement("div")).style.display="flex",r.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),r.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),r.append(l)),c.append(i,r),a.append(c),o.append(n),e.append(o),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(n){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),n.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),n.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),n.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),n.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),n.addEventListener("touchend",function(){var o=this;a=setTimeout(function(){var e=o.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=n.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file +function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||c=e.length?{done:!0}:{done:!1,value:e[c++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(r.data.forEach(function(e){e.encoded_email===c[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===c[t].href||0!==c[t].href.indexOf("mailto:")&&0!==c[t].href.indexOf("tel:"))c[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,c[t])},2e3);else{if(0===c[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==c[t].href.indexOf("tel:"))return 0;e="tel:"}var o=c[t].href.replace(e,""),a=c[t].innerHTML;c[t].innerHTML=a.replace(o,n.decoded_email),c[t].href=e+n.decoded_email,c[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";r.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}c[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=r.data[0];c.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,c)},2e3),c.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(c.innerHTML="Loading...",t&&this.load(t)),c.setAttribute("id","cleantalk-modal-content"),n.append(c),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function p(){_classCallCheck(this,p)}return _createClass(p,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(c),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,r(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),c=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=i(t),b=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,b=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),i=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,c,r,i,l,s,u,d,p=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=p.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,h.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,h.apply(this,n));case 3:return e.n=4,m.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=_(n[1].body,f(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,c=t.querySelector('[name*="apbct__email_id__"]'),r=null,i=(null!==c&&null!==c.value&&(r=c.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===i&&null===c&&null===l||(e.preventDefault(),n=function(){null!==c&&c.parentNode.removeChild(c),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=i,null!==r&&(o.apbct_search_form__honeypot_value=r),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,c=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var c=o.value,r=this.findParentContainer(c);if(r){var i=this.getIdFromHTML(r);if(i===n){var l=r.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"wrappers",[]),this.wrappers=this.findWrappers(),this.wrappers.length<1||this.checkBot()},[{key:"findWrappers",value:function(){return document.querySelectorAll("div.ct-encoded-form-wrapper")}},{key:"checkBot",value:function(){var t=this,e={post_url:document.location.href,referrer:document.referrer};+ctPublic.bot_detector_enabled?e.event_token=apbctLocalStorage.get("bot_detector_event_token"):e.event_javascript_data=getJavascriptClientData(),"rest"===ctPublicFunctions.data__ajax_type?apbct_public_sendREST("force_protection_check_bot",{data:e,method:"POST",callback:function(e){return t.checkBotCallback(e)}}):"admin_ajax"===ctPublicFunctions.data__ajax_type&&(e.action="apbct_force_protection_check_bot",apbct_public_sendAJAX(e,{callback:function(e){return t.checkBotCallback(e)}}))}},{key:"checkBotCallback",value:function(e){if(e.data&&e.data.status&&200!==e.data.status)console.log("ApbctForceProtection connection error occurred"),this.decodeForms();else{if("string"==typeof e)try{e=JSON.parse(e)}catch(e){return console.log("ApbctForceProtection decodeForms error",e),void this.decodeForms()}"object"===_typeof(e)&&e.allow&&1===e.allow?(this.decodeForms(),document.dispatchEvent(new Event("apbctForceProtectionAllowed"))):this.showMessageForBot(e.message)}}},{key:"decodeForms",value:function(){var n;this.wrappers.forEach(function(e){n=e.querySelector("div.ct-encoded-form").dataset.encodedForm;try{var t;n&&"string"==typeof n&&(t=decodeURIComponent(n),e.outerHTML=atob(t))}catch(e){console.log(e)}})}},{key:"showMessageForBot",value:function(t){this.wrappers.forEach(function(e){e.querySelector("div.ct-encoded-form").dataset.encodedForm&&(e.outerHTML='
'+t+"
")})}}]))();function apbctForceProtect(){+ctPublic.settings__forms__force_protection&&void 0!==ApbctForceProtection&&new ApbctForceProtection}ctPublic.data__key_is_ok&&("loading"!==document.readyState?apbctForceProtect():apbct_attach_event_handler(document,"DOMContentLoaded",apbctForceProtect));var ctMouseReadInterval,ctMouseWriteDataInterval,ApbctGatheringData=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"setSessionId",value:function(){var e;apbctSessionStorage.isSet("apbct_session_id")?apbctLocalStorage.set("apbct_page_hits",Number(apbctLocalStorage.get("apbct_page_hits"))+1):(e=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(2,10),apbctSessionStorage.set("apbct_session_id",e,!1),apbctLocalStorage.set("apbct_page_hits",1),document.referrer&&new URL(document.referrer).host!==location.host&&apbctSessionStorage.set("apbct_site_referer",document.referrer,!1))}},{key:"writeReferrersToSessionStorage",value:function(){var e=apbctSessionStorage.get("apbct_session_current_page");!1!==e&&document.location.href!==e&&apbctSessionStorage.set("apbct_prev_referer",e,!1),apbctSessionStorage.set("apbct_session_current_page",document.location.href,!1)}},{key:"setCookiesType",value:function(){var e=apbctLocalStorage.get("ct_cookies_type");e&&e===ctPublic.data__cookies_type||(apbctLocalStorage.set("ct_cookies_type",ctPublic.data__cookies_type),apbctLocalStorage.delete("ct_mouse_moved"),apbctLocalStorage.delete("ct_has_scrolled"))}},{key:"startFieldsListening",value:function(){if(!apbctLocalStorage.isSet("ct_has_key_up")&&!apbctLocalStorage.get("ct_has_key_up")||!apbctLocalStorage.isSet("ct_has_input_focused")&&!apbctLocalStorage.get("ct_has_input_focused")||"native"!==ctPublic.data__cookies_type||void 0===ctGetCookie("ct_has_input_focused")||void 0===ctGetCookie("ct_has_key_up")){var e=ctGetPageForms();if(ctPublic.handled_fields=[],0_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"elementBody",document.querySelector("body")),_defineProperty(this,"collectionForms",document.forms),this.setListeners()},[{key:"setListeners",value:function(){var t=this;this.elementBody.addEventListener("click",function(e){t.checkElementInForms(e,"addClicks")}),this.elementBody.addEventListener("mouseup",function(e){"Range"==document.getSelection().type.toString()&&t.addSelected()}),this.elementBody.addEventListener("mousemove",function(e){t.checkElementInForms(e,"trackMouseMovement")})}},{key:"checkElementInForms",value:function(e,t){for(var n,o=0;o_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"fieldData",{isAutoFill:!1,isUseBuffer:!1,speedDelta:0,firstKeyTimestamp:0,lastKeyTimestamp:0,lastDelta:0,countOfKey:0}),_defineProperty(this,"fields",document.querySelectorAll("textarea[name=comment]")),_defineProperty(this,"data",[])},[{key:"gatheringFields",value:function(){var n=this;Array.prototype.slice.call(this.fields).forEach(function(e,t){n.data.push(Object.assign({},n.fieldData))})}},{key:"setListeners",value:function(){var o=this;this.fields.forEach(function(e,t){e.addEventListener("paste",function(){o.data[t].isUseBuffer=!0})}),this.fields.forEach(function(e,t){e.addEventListener("onautocomplete",function(){o.data[t].isAutoFill=!0})}),this.fields.forEach(function(e,n){e.addEventListener("input",function(){o.data[n].countOfKey++;var e,t=+new Date;1===o.data[n].countOfKey?(o.data[n].lastKeyTimestamp=t,o.data[n].firstKeyTimestamp=t):(e=t-o.data[n].lastKeyTimestamp,2===o.data[n].countOfKey?(o.data[n].lastKeyTimestamp=t,o.data[n].lastDelta=e):2{function o(){_classCallCheck(this,o)}return _createClass(o,null,[{key:"getFrontendDataLog",value:function(){var e=("undefined"!=typeof ctPublicFunctions&&ctPublicFunctions.cookiePrefix?ctPublicFunctions.cookiePrefix:"")+o.LOG_KEY,t=o.LOG_KEY;if(void 0!==apbctLocalStorage&&apbctLocalStorage.get){var n=apbctLocalStorage.get(e)||apbctLocalStorage.get(t)||null;if(n&&"string"==typeof n)try{return JSON.parse(n)}catch(e){return""}return n}n=(n=localStorage.getItem(e))||localStorage.getItem(t)||null;try{return"string"==typeof n?JSON.parse(n):n}catch(e){return""}}},{key:"asDTO",value:function(){return{botd_logic_loaded:o.botdLogicLoaded,botd_wrapper_loaded:o.botdWrapperLoaded,frontend_data_log:"",transport_enabled:1}}},{key:"detectScripts",value:function(){if(o.botdWrapperLoaded&&o.botdLogicLoaded)return!0;for(var e=document.getElementsByTagName("script"),t=0;t .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,c,r,i,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(i=document.createElement("strong")).append(d.phrases.trpHeading),(c=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(r=document.createElement("div")).append(" "),r.append(i),r.append(d.phrases.trpContent1),(i=document.createElement("div")).style.display="flex",i.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),i.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),i.append(l)),c.append(r,i),a.append(c),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file diff --git a/js/apbct-public-bundle_gathering.min.js b/js/apbct-public-bundle_gathering.min.js index 35d911bd5..0b3932296 100644 --- a/js/apbct-public-bundle_gathering.min.js +++ b/js/apbct-public-bundle_gathering.min.js @@ -1 +1 @@ -function ownKeys(t,e){var o,n=Object.keys(t);return Object.getOwnPropertySymbols&&(o=Object.getOwnPropertySymbols(t),e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)),n}function _objectSpread(t){for(var e=1;et||c=e.length?{done:!0}:{done:!1,value:e[c++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var o;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(o="Object"===(o={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:o)||"Set"===o?Array.from(e):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var o=0,n=Array(t);o{var o,e;if(i.data.forEach(function(e){e.encoded_email===c[t].dataset.originalString&&(o=e)}),!1===o.is_allowed)return{v:void 0};if(void 0===c[t].href||0!==c[t].href.indexOf("mailto:")&&0!==c[t].href.indexOf("tel:"))c[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(o,c[t])},2e3);else{if(0===c[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==c[t].href.indexOf("tel:"))return 0;e="tel:"}var n=c[t].href.replace(e,""),a=c[t].innerHTML;c[t].innerHTML=a.replace(n,o.decoded_email),c[t].href=e+o.decoded_email,c[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var o="";i.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(o=e.decoded_email)}),t.innerHTML=o})}c[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var o=i.data[0];c.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(o,c)},2e3),c.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(c.innerHTML="Loading...",t&&this.load(t)),c.setAttribute("id","cleantalk-modal-content"),o.append(c),this.opened=!0},confirm:function(e){var t,o=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var o in e)if(Object.hasOwn(e,o))for(var n=o.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?o||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?o||Boolean(e[t]):o||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):o}},{key:"isWithoutSelector",value:function(e,t){var o,n=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(o=a.n()).done;)n=n||e===o.value}catch(e){a.e(e)}finally{a.f()}return n}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,o=_createForOfIteratorHelper(this.elements);try{for(o.s();!(t=o.n()).done;)t.value.after(e)}catch(e){o.e(e)}finally{o.f()}}},{key:"append",value:function(e){var t,o=_createForOfIteratorHelper(this.elements);try{for(o.s();!(t=o.n()).done;)t.value.append(e)}catch(e){o.e(e)}finally{o.f()}}},{key:"fadeIn",value:function(n){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-o)/n,o=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,o=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(n){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-o)/n,o=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,o=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function n(e){for(var t in _classCallCheck(this,n),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(n,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,o="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(o=e.headers["X-WP-Nonce"]),""!==(o=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:o)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:o,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),o=0;o{function n(){for(var e=arguments.length,t=new Array(e),o=0;o{function a(){for(var e=arguments.length,t=new Array(e),o=0;o{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",o=0,n=Object.entries(this.config);oMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(n){n.addEventListener("click",function(e){var t=n.getAttribute("href"),o=apbctLocalStorage.get("bot_detector_event_token");o&&(-1===t.indexOf("?")?t+="?":t+="&",n.setAttribute("href",t+="ct_bot_detector_event_token="+o))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var o=document.createElement("input"),t=(o.setAttribute("type","hidden"),o.setAttribute("id","apbct_visible_fields_"+t),o.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),o.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(o)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),o=getCleanTalkStorageDataArray(),o=JSON.stringify(o);return o="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(o))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",o),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,o;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(o="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,o+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(o="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,o+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var o="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var n in o){if(10{function u(){_classCallCheck(this,u)}return _createClass(u,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var o=_asyncToGenerator(_regenerator().m(function e(t,o){var n,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:n=_createForOfIteratorHelper(c),e.p=2,n.s();case 3:if((a=n.n()).done)e.n=6;else{if((a=a.value).matches(t,o))return a=a.getForm(),e.n=4,i(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,n.e(a);case 8:return e.p=8,n.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return o.apply(this,arguments)}})(),c=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var o,n,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return o=r(t),f=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(o,{async:!0,callback:e,onErrorCallback:t})});case 3:return n=e.v,(a=void 0!==n.apbct&&+n.apbct.blocked||void 0!==n.data&&void 0!==n.data.message)&&(new ApbctShowForbidden).parseBlockMessage(n),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,f=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),r=function(e){var t,o={action:"cleantalk_force_ajax_check"},n=_createForOfIteratorHelper(e.elements);try{for(n.s();!(t=n.n()).done;){var a=t.value;a.name&&(o[a.name]=a.value)}}catch(e){n.e(e)}finally{n.f()}return+ctPublic.bot_detector_enabled?o.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):o.ct_no_cookie_hidden_field=getNoCookieData(),o};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,o,n,a,c,i,r,l,s,u=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=u.length,o=new Array(t),n=0;n!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof o[0]?o[0]:(null==(a=o[0])?void 0:a.url)||""))return e.a(2,m.apply(this,o));e.n=2;break;case 2:if(o&&o[0]&&o[1]&&o[1].body){e.n=3;break}return e.a(2,m.apply(this,o));case 3:return e.n=4,_.processFetch(o);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return o[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{o[1].body=p(o[1].body,d(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return o.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var o,n,a,c=t.querySelector('[name*="apbct__email_id__"]'),i=null,r=(null!==c&&null!==c.value&&(i=c.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===r&&null===c&&null===l||(e.preventDefault(),o=function(){null!==c&&c.parentNode.removeChild(c),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},n=r,null!==i&&(n.apbct_search_form__honeypot_value=i),n.ct_bot_detector_event_token=l,"string"==typeof n.apbct_pixel_url&&-1!==n.apbct_pixel_url.indexOf("%3A")&&(n.apbct_pixel_url=decodeURIComponent(n.apbct_pixel_url)),void 0!==(a=JSON.stringify(n))&&0!==a.length?ctSetAlternativeCookie(a,{callback:o,onErrorCallback:o,forceAltCookies:!0}):o())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var n=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,o){n(t)}):jQuery(document).ajaxComplete(function(e,t,o){n(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&n(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,o="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(o=e.comment),o=void 0!==e.data&&void 0!==(e=e.data).message?e.message:o)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:o}})),cleantalkModal.loaded=o,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var n=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&n.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,c=n;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),o=this.getIdFromAjax(e);if(o){var n,a=_createForOfIteratorHelper(t);try{for(a.s();!(n=a.n()).done;){var c=n.value,i=this.findParentContainer(c);if(i){var r=this.getIdFromHTML(i);if(r===o){var l=i.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,o=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,o=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t_createClass(function e(){_classCallCheck(this,e)},[{key:"setSessionId",value:function(){var e;apbctSessionStorage.isSet("apbct_session_id")?apbctLocalStorage.set("apbct_page_hits",Number(apbctLocalStorage.get("apbct_page_hits"))+1):(e=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(2,10),apbctSessionStorage.set("apbct_session_id",e,!1),apbctLocalStorage.set("apbct_page_hits",1),document.referrer&&new URL(document.referrer).host!==location.host&&apbctSessionStorage.set("apbct_site_referer",document.referrer,!1))}},{key:"writeReferrersToSessionStorage",value:function(){var e=apbctSessionStorage.get("apbct_session_current_page");!1!==e&&document.location.href!==e&&apbctSessionStorage.set("apbct_prev_referer",e,!1),apbctSessionStorage.set("apbct_session_current_page",document.location.href,!1)}},{key:"setCookiesType",value:function(){var e=apbctLocalStorage.get("ct_cookies_type");e&&e===ctPublic.data__cookies_type||(apbctLocalStorage.set("ct_cookies_type",ctPublic.data__cookies_type),apbctLocalStorage.delete("ct_mouse_moved"),apbctLocalStorage.delete("ct_has_scrolled"))}},{key:"startFieldsListening",value:function(){if(!apbctLocalStorage.isSet("ct_has_key_up")&&!apbctLocalStorage.get("ct_has_key_up")||!apbctLocalStorage.isSet("ct_has_input_focused")&&!apbctLocalStorage.get("ct_has_input_focused")||"native"!==ctPublic.data__cookies_type||void 0===ctGetCookie("ct_has_input_focused")||void 0===ctGetCookie("ct_has_key_up")){var e=ctGetPageForms();if(ctPublic.handled_fields=[],0_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"elementBody",document.querySelector("body")),_defineProperty(this,"collectionForms",document.forms),this.setListeners()},[{key:"setListeners",value:function(){var t=this;this.elementBody.addEventListener("click",function(e){t.checkElementInForms(e,"addClicks")}),this.elementBody.addEventListener("mouseup",function(e){"Range"==document.getSelection().type.toString()&&t.addSelected()}),this.elementBody.addEventListener("mousemove",function(e){t.checkElementInForms(e,"trackMouseMovement")})}},{key:"checkElementInForms",value:function(e,t){for(var o,n=0;n_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"fieldData",{isAutoFill:!1,isUseBuffer:!1,speedDelta:0,firstKeyTimestamp:0,lastKeyTimestamp:0,lastDelta:0,countOfKey:0}),_defineProperty(this,"fields",document.querySelectorAll("textarea[name=comment]")),_defineProperty(this,"data",[])},[{key:"gatheringFields",value:function(){var o=this;Array.prototype.slice.call(this.fields).forEach(function(e,t){o.data.push(Object.assign({},o.fieldData))})}},{key:"setListeners",value:function(){var n=this;this.fields.forEach(function(e,t){e.addEventListener("paste",function(){n.data[t].isUseBuffer=!0})}),this.fields.forEach(function(e,t){e.addEventListener("onautocomplete",function(){n.data[t].isAutoFill=!0})}),this.fields.forEach(function(e,o){e.addEventListener("input",function(){n.data[o].countOfKey++;var e,t=+new Date;1===n.data[o].countOfKey?(n.data[o].lastKeyTimestamp=t,n.data[o].firstKeyTimestamp=t):(e=t-n.data[o].lastKeyTimestamp,2===n.data[o].countOfKey?(n.data[o].lastKeyTimestamp=t,n.data[o].lastDelta=e):2 .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var o,n,a,c,i,r,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((o=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(n=document.createElement("img")).setAttribute("src",d.imgPersonUrl),n.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(r=document.createElement("strong")).append(d.phrases.trpHeading),(c=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(i=document.createElement("div")).append(" "),i.append(r),i.append(d.phrases.trpContent1),(r=document.createElement("div")).style.display="flex",r.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),r.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),r.append(l)),c.append(i,r),a.append(c),o.append(n),e.append(o),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(n){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),n.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),n.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),n.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),n.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),n.addEventListener("touchend",function(){var o=this;a=setTimeout(function(){var e=o.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=n.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file +function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(c.data.forEach(function(e){e.encoded_email===r[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===r[t].href||0!==r[t].href.indexOf("mailto:")&&0!==r[t].href.indexOf("tel:"))r[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r[t])},2e3);else{if(0===r[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==r[t].href.indexOf("tel:"))return 0;e="tel:"}var o=r[t].href.replace(e,""),a=r[t].innerHTML;r[t].innerHTML=a.replace(o,n.decoded_email),r[t].href=e+n.decoded_email,r[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";c.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}r[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=c.data[0];r.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r)},2e3),r.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(r.innerHTML="Loading...",t&&this.load(t)),r.setAttribute("id","cleantalk-modal-content"),n.append(r),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function p(){_classCallCheck(this,p)}return _createClass(p,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(r),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,c(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),r=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=i(t),m=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,m=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),i=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,r,c,i,l,s,u,d,p=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=p.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,h.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,h.apply(this,n));case 3:return e.n=4,b.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=f(n[1].body,_(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,r=t.querySelector('[name*="apbct__email_id__"]'),c=null,i=(null!==r&&null!==r.value&&(c=r.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===i&&null===r&&null===l||(e.preventDefault(),n=function(){null!==r&&r.parentNode.removeChild(r),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=i,null!==c&&(o.apbct_search_form__honeypot_value=c),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,r=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var r=o.value,c=this.findParentContainer(r);if(c){var i=this.getIdFromHTML(c);if(i===n){var l=c.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t_createClass(function e(){_classCallCheck(this,e)},[{key:"setSessionId",value:function(){var e;apbctSessionStorage.isSet("apbct_session_id")?apbctLocalStorage.set("apbct_page_hits",Number(apbctLocalStorage.get("apbct_page_hits"))+1):(e=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(2,10),apbctSessionStorage.set("apbct_session_id",e,!1),apbctLocalStorage.set("apbct_page_hits",1),document.referrer&&new URL(document.referrer).host!==location.host&&apbctSessionStorage.set("apbct_site_referer",document.referrer,!1))}},{key:"writeReferrersToSessionStorage",value:function(){var e=apbctSessionStorage.get("apbct_session_current_page");!1!==e&&document.location.href!==e&&apbctSessionStorage.set("apbct_prev_referer",e,!1),apbctSessionStorage.set("apbct_session_current_page",document.location.href,!1)}},{key:"setCookiesType",value:function(){var e=apbctLocalStorage.get("ct_cookies_type");e&&e===ctPublic.data__cookies_type||(apbctLocalStorage.set("ct_cookies_type",ctPublic.data__cookies_type),apbctLocalStorage.delete("ct_mouse_moved"),apbctLocalStorage.delete("ct_has_scrolled"))}},{key:"startFieldsListening",value:function(){if(!apbctLocalStorage.isSet("ct_has_key_up")&&!apbctLocalStorage.get("ct_has_key_up")||!apbctLocalStorage.isSet("ct_has_input_focused")&&!apbctLocalStorage.get("ct_has_input_focused")||"native"!==ctPublic.data__cookies_type||void 0===ctGetCookie("ct_has_input_focused")||void 0===ctGetCookie("ct_has_key_up")){var e=ctGetPageForms();if(ctPublic.handled_fields=[],0_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"elementBody",document.querySelector("body")),_defineProperty(this,"collectionForms",document.forms),this.setListeners()},[{key:"setListeners",value:function(){var t=this;this.elementBody.addEventListener("click",function(e){t.checkElementInForms(e,"addClicks")}),this.elementBody.addEventListener("mouseup",function(e){"Range"==document.getSelection().type.toString()&&t.addSelected()}),this.elementBody.addEventListener("mousemove",function(e){t.checkElementInForms(e,"trackMouseMovement")})}},{key:"checkElementInForms",value:function(e,t){for(var n,o=0;o_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"fieldData",{isAutoFill:!1,isUseBuffer:!1,speedDelta:0,firstKeyTimestamp:0,lastKeyTimestamp:0,lastDelta:0,countOfKey:0}),_defineProperty(this,"fields",document.querySelectorAll("textarea[name=comment]")),_defineProperty(this,"data",[])},[{key:"gatheringFields",value:function(){var n=this;Array.prototype.slice.call(this.fields).forEach(function(e,t){n.data.push(Object.assign({},n.fieldData))})}},{key:"setListeners",value:function(){var o=this;this.fields.forEach(function(e,t){e.addEventListener("paste",function(){o.data[t].isUseBuffer=!0})}),this.fields.forEach(function(e,t){e.addEventListener("onautocomplete",function(){o.data[t].isAutoFill=!0})}),this.fields.forEach(function(e,n){e.addEventListener("input",function(){o.data[n].countOfKey++;var e,t=+new Date;1===o.data[n].countOfKey?(o.data[n].lastKeyTimestamp=t,o.data[n].firstKeyTimestamp=t):(e=t-o.data[n].lastKeyTimestamp,2===o.data[n].countOfKey?(o.data[n].lastKeyTimestamp=t,o.data[n].lastDelta=e):2{function o(){_classCallCheck(this,o)}return _createClass(o,null,[{key:"getFrontendDataLog",value:function(){var e=("undefined"!=typeof ctPublicFunctions&&ctPublicFunctions.cookiePrefix?ctPublicFunctions.cookiePrefix:"")+o.LOG_KEY,t=o.LOG_KEY;if(void 0!==apbctLocalStorage&&apbctLocalStorage.get){var n=apbctLocalStorage.get(e)||apbctLocalStorage.get(t)||null;if(n&&"string"==typeof n)try{return JSON.parse(n)}catch(e){return""}return n}n=(n=localStorage.getItem(e))||localStorage.getItem(t)||null;try{return"string"==typeof n?JSON.parse(n):n}catch(e){return""}}},{key:"asDTO",value:function(){return{botd_logic_loaded:o.botdLogicLoaded,botd_wrapper_loaded:o.botdWrapperLoaded,frontend_data_log:"",transport_enabled:1}}},{key:"detectScripts",value:function(){if(o.botdWrapperLoaded&&o.botdLogicLoaded)return!0;for(var e=document.getElementsByTagName("script"),t=0;t .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,r,c,i,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(i=document.createElement("strong")).append(d.phrases.trpHeading),(r=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(c=document.createElement("div")).append(" "),c.append(i),c.append(d.phrases.trpContent1),(i=document.createElement("div")).style.display="flex",i.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),i.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),i.append(l)),r.append(c,i),a.append(r),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file diff --git a/js/apbct-public-bundle_int-protection.min.js b/js/apbct-public-bundle_int-protection.min.js index f45b71d6f..0ade9e80c 100644 --- a/js/apbct-public-bundle_int-protection.min.js +++ b/js/apbct-public-bundle_int-protection.min.js @@ -1 +1 @@ -function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(i.data.forEach(function(e){e.encoded_email===r[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===r[t].href||0!==r[t].href.indexOf("mailto:")&&0!==r[t].href.indexOf("tel:"))r[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r[t])},2e3);else{if(0===r[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==r[t].href.indexOf("tel:"))return 0;e="tel:"}var o=r[t].href.replace(e,""),a=r[t].innerHTML;r[t].innerHTML=a.replace(o,n.decoded_email),r[t].href=e+n.decoded_email,r[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";i.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}r[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=i.data[0];r.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r)},2e3),r.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(r.innerHTML="Loading...",t&&this.load(t)),r.setAttribute("id","cleantalk-modal-content"),n.append(r),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function u(){_classCallCheck(this,u)}return _createClass(u,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(r),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,i(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),r=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=c(t),f=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,f=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),c=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,r,i,c,l,s,u=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=u.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,m.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,m.apply(this,n));case 3:return e.n=4,_.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=p(n[1].body,d(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,r=t.querySelector('[name*="apbct__email_id__"]'),i=null,c=(null!==r&&null!==r.value&&(i=r.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===c&&null===r&&null===l||(e.preventDefault(),n=function(){null!==r&&r.parentNode.removeChild(r),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=c,null!==i&&(o.apbct_search_form__honeypot_value=i),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,r=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var r=o.value,i=this.findParentContainer(r);if(i){var c=this.getIdFromHTML(i);if(c===n){var l=i.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,r,i,c,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(c=document.createElement("strong")).append(d.phrases.trpHeading),(r=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(i=document.createElement("div")).append(" "),i.append(c),i.append(d.phrases.trpContent1),(c=document.createElement("div")).style.display="flex",c.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),c.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),c.append(l)),r.append(i,c),a.append(r),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file +function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(i.data.forEach(function(e){e.encoded_email===r[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===r[t].href||0!==r[t].href.indexOf("mailto:")&&0!==r[t].href.indexOf("tel:"))r[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r[t])},2e3);else{if(0===r[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==r[t].href.indexOf("tel:"))return 0;e="tel:"}var o=r[t].href.replace(e,""),a=r[t].innerHTML;r[t].innerHTML=a.replace(o,n.decoded_email),r[t].href=e+n.decoded_email,r[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";i.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}r[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=i.data[0];r.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r)},2e3),r.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(r.innerHTML="Loading...",t&&this.load(t)),r.setAttribute("id","cleantalk-modal-content"),n.append(r),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function p(){_classCallCheck(this,p)}return _createClass(p,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(r),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,i(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),r=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=c(t),b=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,b=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),c=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,r,i,c,l,s,u,d,p=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=p.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,h.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,h.apply(this,n));case 3:return e.n=4,m.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=_(n[1].body,f(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,r=t.querySelector('[name*="apbct__email_id__"]'),i=null,c=(null!==r&&null!==r.value&&(i=r.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===c&&null===r&&null===l||(e.preventDefault(),n=function(){null!==r&&r.parentNode.removeChild(r),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=c,null!==i&&(o.apbct_search_form__honeypot_value=i),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,r=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var r=o.value,i=this.findParentContainer(r);if(i){var c=this.getIdFromHTML(i);if(c===n){var l=i.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t{function o(){_classCallCheck(this,o)}return _createClass(o,null,[{key:"getFrontendDataLog",value:function(){var e=("undefined"!=typeof ctPublicFunctions&&ctPublicFunctions.cookiePrefix?ctPublicFunctions.cookiePrefix:"")+o.LOG_KEY,t=o.LOG_KEY;if(void 0!==apbctLocalStorage&&apbctLocalStorage.get){var n=apbctLocalStorage.get(e)||apbctLocalStorage.get(t)||null;if(n&&"string"==typeof n)try{return JSON.parse(n)}catch(e){return""}return n}n=(n=localStorage.getItem(e))||localStorage.getItem(t)||null;try{return"string"==typeof n?JSON.parse(n):n}catch(e){return""}}},{key:"asDTO",value:function(){return{botd_logic_loaded:o.botdLogicLoaded,botd_wrapper_loaded:o.botdWrapperLoaded,frontend_data_log:"",transport_enabled:1}}},{key:"detectScripts",value:function(){if(o.botdWrapperLoaded&&o.botdLogicLoaded)return!0;for(var e=document.getElementsByTagName("script"),t=0;t .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,r,i,c,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(c=document.createElement("strong")).append(d.phrases.trpHeading),(r=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(i=document.createElement("div")).append(" "),i.append(c),i.append(d.phrases.trpContent1),(c=document.createElement("div")).style.display="flex",c.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),c.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),c.append(l)),r.append(i,c),a.append(r),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file diff --git a/js/apbct-public-bundle_int-protection_gathering.min.js b/js/apbct-public-bundle_int-protection_gathering.min.js index 8b8df15bf..ad981d2ae 100644 --- a/js/apbct-public-bundle_int-protection_gathering.min.js +++ b/js/apbct-public-bundle_int-protection_gathering.min.js @@ -1 +1 @@ -function ownKeys(t,e){var o,n=Object.keys(t);return Object.getOwnPropertySymbols&&(o=Object.getOwnPropertySymbols(t),e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)),n}function _objectSpread(t){for(var e=1;et||c=e.length?{done:!0}:{done:!1,value:e[c++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var o;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(o="Object"===(o={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:o)||"Set"===o?Array.from(e):"Arguments"===o||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(o)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var o=0,n=Array(t);o{var o,e;if(i.data.forEach(function(e){e.encoded_email===c[t].dataset.originalString&&(o=e)}),!1===o.is_allowed)return{v:void 0};if(void 0===c[t].href||0!==c[t].href.indexOf("mailto:")&&0!==c[t].href.indexOf("tel:"))c[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(o,c[t])},2e3);else{if(0===c[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==c[t].href.indexOf("tel:"))return 0;e="tel:"}var n=c[t].href.replace(e,""),a=c[t].innerHTML;c[t].innerHTML=a.replace(n,o.decoded_email),c[t].href=e+o.decoded_email,c[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var o="";i.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(o=e.decoded_email)}),t.innerHTML=o})}c[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var o=i.data[0];c.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(o,c)},2e3),c.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(c.innerHTML="Loading...",t&&this.load(t)),c.setAttribute("id","cleantalk-modal-content"),o.append(c),this.opened=!0},confirm:function(e){var t,o=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var o in e)if(Object.hasOwn(e,o))for(var n=o.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?o||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?o||Boolean(e[t]):o||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):o}},{key:"isWithoutSelector",value:function(e,t){var o,n=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(o=a.n()).done;)n=n||e===o.value}catch(e){a.e(e)}finally{a.f()}return n}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,o=_createForOfIteratorHelper(this.elements);try{for(o.s();!(t=o.n()).done;)t.value.after(e)}catch(e){o.e(e)}finally{o.f()}}},{key:"append",value:function(e){var t,o=_createForOfIteratorHelper(this.elements);try{for(o.s();!(t=o.n()).done;)t.value.append(e)}catch(e){o.e(e)}finally{o.f()}}},{key:"fadeIn",value:function(n){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-o)/n,o=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,o=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(n){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-o)/n,o=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,o=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function n(e){for(var t in _classCallCheck(this,n),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(n,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,o="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(o=e.headers["X-WP-Nonce"]),""!==(o=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:o)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:o,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),o=0;o{function n(){for(var e=arguments.length,t=new Array(e),o=0;o{function a(){for(var e=arguments.length,t=new Array(e),o=0;o{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",o=0,n=Object.entries(this.config);oMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(n){n.addEventListener("click",function(e){var t=n.getAttribute("href"),o=apbctLocalStorage.get("bot_detector_event_token");o&&(-1===t.indexOf("?")?t+="?":t+="&",n.setAttribute("href",t+="ct_bot_detector_event_token="+o))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var o=document.createElement("input"),t=(o.setAttribute("type","hidden"),o.setAttribute("id","apbct_visible_fields_"+t),o.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),o.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(o)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),o=getCleanTalkStorageDataArray(),o=JSON.stringify(o);return o="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(o))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",o),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,o;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(o="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,o+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(o="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,o+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var o="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var n in o){if(10{function u(){_classCallCheck(this,u)}return _createClass(u,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var o=_asyncToGenerator(_regenerator().m(function e(t,o){var n,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:n=_createForOfIteratorHelper(c),e.p=2,n.s();case 3:if((a=n.n()).done)e.n=6;else{if((a=a.value).matches(t,o))return a=a.getForm(),e.n=4,i(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,n.e(a);case 8:return e.p=8,n.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return o.apply(this,arguments)}})(),c=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var o,n,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return o=r(t),f=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(o,{async:!0,callback:e,onErrorCallback:t})});case 3:return n=e.v,(a=void 0!==n.apbct&&+n.apbct.blocked||void 0!==n.data&&void 0!==n.data.message)&&(new ApbctShowForbidden).parseBlockMessage(n),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,f=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),r=function(e){var t,o={action:"cleantalk_force_ajax_check"},n=_createForOfIteratorHelper(e.elements);try{for(n.s();!(t=n.n()).done;){var a=t.value;a.name&&(o[a.name]=a.value)}}catch(e){n.e(e)}finally{n.f()}return+ctPublic.bot_detector_enabled?o.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):o.ct_no_cookie_hidden_field=getNoCookieData(),o};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,o,n,a,c,i,r,l,s,u=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=u.length,o=new Array(t),n=0;n!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof o[0]?o[0]:(null==(a=o[0])?void 0:a.url)||""))return e.a(2,m.apply(this,o));e.n=2;break;case 2:if(o&&o[0]&&o[1]&&o[1].body){e.n=3;break}return e.a(2,m.apply(this,o));case 3:return e.n=4,_.processFetch(o);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return o[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{o[1].body=p(o[1].body,d(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return o.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var o,n,a,c=t.querySelector('[name*="apbct__email_id__"]'),i=null,r=(null!==c&&null!==c.value&&(i=c.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===r&&null===c&&null===l||(e.preventDefault(),o=function(){null!==c&&c.parentNode.removeChild(c),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},n=r,null!==i&&(n.apbct_search_form__honeypot_value=i),n.ct_bot_detector_event_token=l,"string"==typeof n.apbct_pixel_url&&-1!==n.apbct_pixel_url.indexOf("%3A")&&(n.apbct_pixel_url=decodeURIComponent(n.apbct_pixel_url)),void 0!==(a=JSON.stringify(n))&&0!==a.length?ctSetAlternativeCookie(a,{callback:o,onErrorCallback:o,forceAltCookies:!0}):o())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var n=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,o){n(t)}):jQuery(document).ajaxComplete(function(e,t,o){n(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&n(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,o="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(o=e.comment),o=void 0!==e.data&&void 0!==(e=e.data).message?e.message:o)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:o}})),cleantalkModal.loaded=o,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var n=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&n.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,c=n;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),o=this.getIdFromAjax(e);if(o){var n,a=_createForOfIteratorHelper(t);try{for(a.s();!(n=a.n()).done;){var c=n.value,i=this.findParentContainer(c);if(i){var r=this.getIdFromHTML(i);if(r===o){var l=i.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,o=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,o=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t_createClass(function e(){_classCallCheck(this,e)},[{key:"setSessionId",value:function(){var e;apbctSessionStorage.isSet("apbct_session_id")?apbctLocalStorage.set("apbct_page_hits",Number(apbctLocalStorage.get("apbct_page_hits"))+1):(e=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(2,10),apbctSessionStorage.set("apbct_session_id",e,!1),apbctLocalStorage.set("apbct_page_hits",1),document.referrer&&new URL(document.referrer).host!==location.host&&apbctSessionStorage.set("apbct_site_referer",document.referrer,!1))}},{key:"writeReferrersToSessionStorage",value:function(){var e=apbctSessionStorage.get("apbct_session_current_page");!1!==e&&document.location.href!==e&&apbctSessionStorage.set("apbct_prev_referer",e,!1),apbctSessionStorage.set("apbct_session_current_page",document.location.href,!1)}},{key:"setCookiesType",value:function(){var e=apbctLocalStorage.get("ct_cookies_type");e&&e===ctPublic.data__cookies_type||(apbctLocalStorage.set("ct_cookies_type",ctPublic.data__cookies_type),apbctLocalStorage.delete("ct_mouse_moved"),apbctLocalStorage.delete("ct_has_scrolled"))}},{key:"startFieldsListening",value:function(){if(!apbctLocalStorage.isSet("ct_has_key_up")&&!apbctLocalStorage.get("ct_has_key_up")||!apbctLocalStorage.isSet("ct_has_input_focused")&&!apbctLocalStorage.get("ct_has_input_focused")||"native"!==ctPublic.data__cookies_type||void 0===ctGetCookie("ct_has_input_focused")||void 0===ctGetCookie("ct_has_key_up")){var e=ctGetPageForms();if(ctPublic.handled_fields=[],0_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"elementBody",document.querySelector("body")),_defineProperty(this,"collectionForms",document.forms),this.setListeners()},[{key:"setListeners",value:function(){var t=this;this.elementBody.addEventListener("click",function(e){t.checkElementInForms(e,"addClicks")}),this.elementBody.addEventListener("mouseup",function(e){"Range"==document.getSelection().type.toString()&&t.addSelected()}),this.elementBody.addEventListener("mousemove",function(e){t.checkElementInForms(e,"trackMouseMovement")})}},{key:"checkElementInForms",value:function(e,t){for(var o,n=0;n_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"fieldData",{isAutoFill:!1,isUseBuffer:!1,speedDelta:0,firstKeyTimestamp:0,lastKeyTimestamp:0,lastDelta:0,countOfKey:0}),_defineProperty(this,"fields",document.querySelectorAll("textarea[name=comment]")),_defineProperty(this,"data",[])},[{key:"gatheringFields",value:function(){var o=this;Array.prototype.slice.call(this.fields).forEach(function(e,t){o.data.push(Object.assign({},o.fieldData))})}},{key:"setListeners",value:function(){var n=this;this.fields.forEach(function(e,t){e.addEventListener("paste",function(){n.data[t].isUseBuffer=!0})}),this.fields.forEach(function(e,t){e.addEventListener("onautocomplete",function(){n.data[t].isAutoFill=!0})}),this.fields.forEach(function(e,o){e.addEventListener("input",function(){n.data[o].countOfKey++;var e,t=+new Date;1===n.data[o].countOfKey?(n.data[o].lastKeyTimestamp=t,n.data[o].firstKeyTimestamp=t):(e=t-n.data[o].lastKeyTimestamp,2===n.data[o].countOfKey?(n.data[o].lastKeyTimestamp=t,n.data[o].lastDelta=e):2 .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var o,n,a,c,i,r,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((o=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(n=document.createElement("img")).setAttribute("src",d.imgPersonUrl),n.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(r=document.createElement("strong")).append(d.phrases.trpHeading),(c=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(i=document.createElement("div")).append(" "),i.append(r),i.append(d.phrases.trpContent1),(r=document.createElement("div")).style.display="flex",r.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),r.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),r.append(l)),c.append(i,r),a.append(c),o.append(n),e.append(o),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(n){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),n.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),n.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),n.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),n.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),n.addEventListener("touchend",function(){var o=this;a=setTimeout(function(){var e=o.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=n.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file +function ownKeys(t,e){var n,o=Object.keys(t);return Object.getOwnPropertySymbols&&(n=Object.getOwnPropertySymbols(t),e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),o.push.apply(o,n)),o}function _objectSpread(t){for(var e=1;et||r=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:t};throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _unsupportedIterableToArray(e,t){var n;if(e)return"string"==typeof e?_arrayLikeToArray(e,t):"Map"===(n="Object"===(n={}.toString.call(e).slice(8,-1))&&e.constructor?e.constructor.name:n)||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(e,t):void 0}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=Array(t);n{var n,e;if(c.data.forEach(function(e){e.encoded_email===r[t].dataset.originalString&&(n=e)}),!1===n.is_allowed)return{v:void 0};if(void 0===r[t].href||0!==r[t].href.indexOf("mailto:")&&0!==r[t].href.indexOf("tel:"))r[t].classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r[t])},2e3);else{if(0===r[t].href.indexOf("mailto:"))e="mailto:";else{if(0!==r[t].href.indexOf("tel:"))return 0;e="tel:"}var o=r[t].href.replace(e,""),a=r[t].innerHTML;r[t].innerHTML=a.replace(o,n.decoded_email),r[t].href=e+n.decoded_email,r[t].querySelectorAll("span.apbct-email-encoder").forEach(function(t){var n="";c.data.forEach(function(e){e.encoded_email===t.dataset.originalString&&(n=e.decoded_email)}),t.innerHTML=n})}r[t].removeEventListener("click",ctFillDecodedEmailHandler)})(t))&&e)return e.v}else{var n=c.data[0];r.classList.add("no-blur"),setTimeout(function(){ctProcessDecodedDataResult(n,r)},2e3),r.removeEventListener("click",ctFillDecodedEmailHandler)}}function ctProcessDecodedDataResult(e,t){t.setAttribute("title",""),t.removeAttribute("style"),ctFillDecodedEmail(t,e.decoded_email)}function ctFillDecodedEmail(e,t){e.innerHTML=e.innerHTML.replace(/.+?(
)/,t+"$1")}document.addEventListener("DOMContentLoaded",function(){var e=document.querySelectorAll("[data-original-string]");if("undefined"!=typeof ctPublic&&(ctPublic.encodedEmailNodes=e),e.length)for(var t=0;t$1')):(r.innerHTML="Loading...",t&&this.load(t)),r.setAttribute("id","cleantalk-modal-content"),n.append(r),this.opened=!0},confirm:function(e){var t,n=1_createClass(function e(t){_classCallCheck(this,e),_defineProperty(this,"ajax_parameters",{}),_defineProperty(this,"restParameters",{}),_defineProperty(this,"selector",null),_defineProperty(this,"elements",[]),_defineProperty(this,"eventCallback",void 0),_defineProperty(this,"eventSelector",void 0),_defineProperty(this,"event",void 0),this.select(t)},[{key:"select",value:function(e){return e instanceof HTMLCollection?(this.selector=null,this.elements=[],this.elements=Array.prototype.slice.call(e)):"object"===_typeof(e)?(this.selector=null,this.elements=[],this.elements[0]=e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect(),this}},{key:"addElement",value:function(e){"object"===_typeof(e)?this.elements.push(e):"string"==typeof e?(this.selector=e,this.elements=Array.prototype.slice.call(document.querySelectorAll(e))):this.deselect()}},{key:"push",value:function(e){this.elements.push(e)}},{key:"reduce",value:function(){this.elements=this.elements.slice(0,-1)}},{key:"deselect",value:function(){this.elements=[]}},{key:"css",value:function(e,t){if(t=t||!1,"object"===_typeof(e)){for(var n in e)if(Object.hasOwn(e,n))for(var o=n.replace(/([-_][a-z])/g,function(e){return e.toUpperCase().replace("-","").replace("_","")}),a=0;a(e=document.createElement(e).constructor,!Boolean(~[HTMLElement,HTMLUnknownElement].indexOf(e))))(t)?n||e.tagName.toLowerCase()===t.toLowerCase():t.match(/^[a-z]/)?n||Boolean(e[t]):n||(null!==this.selector?null!==document.querySelector(this.selector+t):this.isWithoutSelector(e,t)):n}},{key:"isWithoutSelector",value:function(e,t){var n,o=!1,a=_createForOfIteratorHelper(document.querySelectorAll(t));try{for(a.s();!(n=a.n()).done;)o=o||e===n.value}catch(e){a.e(e)}finally{a.f()}return o}},{key:"filter",value:function(e){this.selector=null;for(var t=this.elements.length-1;0<=t;t--)this.isElem(this.elements[t],e)||this.elements.splice(Number(t),1);return this}},{key:"parent",value:function(e){return this.select(this.elements[0].parentElement),void 0===e||this.is(e)||this.deselect(),this}},{key:"parents",value:function(e){for(this.select(this.elements[0]);null!==this.elements[this.elements.length-1].parentElement;)this.push(this.elements[this.elements.length-1].parentElement);return this.elements.splice(0,1),void 0!==e&&this.filter(e),this}},{key:"children",value:function(e){return this.select(this.elements[0].children),void 0!==e&&this.filter(e),this}},{key:"siblings",value:function(e){var t=this.elements[0];return this.parent(),this.children(e),this.elements.splice(this.elements.indexOf(t),1),this}},{key:"remove",value:function(){var e,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(e=t.n()).done;)e.value.remove()}catch(e){t.e(e)}finally{t.f()}}},{key:"after",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.after(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"append",value:function(e){var t,n=_createForOfIteratorHelper(this.elements);try{for(n.s();!(t=n.n()).done;)t.value.append(e)}catch(e){n.e(e)}finally{n.f()}}},{key:"fadeIn",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity+(new Date-n)/o,n=+new Date,+t.style.opacity<1&&(window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16))}var t=a.value,n=(t.style.opacity=0,t.style.display="block",+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}},{key:"fadeOut",value:function(o){var a,t=_createForOfIteratorHelper(this.elements);try{for(t.s();!(a=t.n()).done;)(()=>{function e(){t.style.opacity=+t.style.opacity-(new Date-n)/o,n=+new Date,0<+t.style.opacity?window.requestAnimationFrame&&requestAnimationFrame(e)||setTimeout(e,16):t.style.display="none"}var t=a.value,n=(t.style.opacity=1,+new Date);e()})()}catch(e){t.e(e)}finally{t.f()}}}]))());function selectActualNonce(){var e="";return ctPublicFunctions.hasOwnProperty("_fresh_nonce")&&"string"==typeof ctPublicFunctions._fresh_nonce&&0{function o(e){for(var t in _classCallCheck(this,o),_defineProperty(this,"xhr",new XMLHttpRequest),_defineProperty(this,"method","POST"),_defineProperty(this,"url",""),_defineProperty(this,"async",!0),_defineProperty(this,"user",null),_defineProperty(this,"password",null),_defineProperty(this,"data",{}),_defineProperty(this,"button",null),_defineProperty(this,"spinner",null),_defineProperty(this,"progressbar",null),_defineProperty(this,"context",this),_defineProperty(this,"callback",null),_defineProperty(this,"onErrorCallback",null),_defineProperty(this,"responseType","json"),_defineProperty(this,"headers",{}),_defineProperty(this,"timeout",15e3),_defineProperty(this,"methods_to_convert_data_to_URL",["GET","HEAD"]),_defineProperty(this,"body",null),_defineProperty(this,"http_code",0),_defineProperty(this,"status_text",""),e)void 0!==this[t]&&(this[t]=e[t]);if(this.prepare(),Object.keys(this.data).length&&(this.deleteDoubleJSONEncoding(this.data),this.convertData()),!this.url)return console.log("%cXHR%c not URL provided","color: red; font-weight: bold;","color: grey; font-weight: normal;"),!1;this.xhr.open(this.method,this.url,this.async,this.user,this.password),this.setHeaders(),this.xhr.responseType=this.responseType,this.xhr.timeout=this.timeout,this.xhr.onreadystatechange=function(){this.isWpNonceError()?this.getFreshNonceAndRerunXHR(e):this.onReadyStateChange()}.bind(this),this.xhr.onload=function(){this.onLoad()}.bind(this),this.xhr.onprogress=function(e){this.onProgress(e)}.bind(this),this.xhr.onerror=function(){this.onError()}.bind(this),this.xhr.ontimeout=function(){this.onTimeout()}.bind(this),this.xhr.send(this.body)}return _createClass(o,[{key:"prepare",value:function(){this.button&&(this.button.setAttribute("disabled","disabled"),this.button.style.cursor="not-allowed"),this.spinner&&(this.spinner.style.display="inline")}},{key:"complete",value:function(){this.http_code=this.xhr.status,this.status_text=this.xhr.statusText,this.button&&(this.button.removeAttribute("disabled"),this.button.style.cursor="auto"),this.spinner&&(this.spinner.style.display="none"),this.progressbar&&this.progressbar.fadeOut("slow")}},{key:"onReadyStateChange",value:function(){null!==this.on_ready_state_change&&"function"==typeof this.on_ready_state_change&&this.on_ready_state_change()}},{key:"onProgress",value:function(e){null!==this.on_progress&&"function"==typeof this.on_progress&&this.on_progress()}},{key:"onError",value:function(){console.log("error"),this.complete(),this.error(this.http_code,this.status_text),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback(this.status_text)}},{key:"onTimeout",value:function(){this.complete(),this.error(0,"timeout"),null!==this.onErrorCallback&&"function"==typeof this.onErrorCallback&&this.onErrorCallback("Timeout")}},{key:"onLoad",value:function(){if(this.complete(),"json"===this.responseType){if(null===this.xhr.response)return this.error(this.http_code,this.status_text,"No response"),!1;if(void 0!==this.xhr.response.error)return this.error(this.http_code,this.status_text,this.xhr.response.error),!1}null!==this.callback&&"function"==typeof this.callback&&this.callback.call(this.context,this.xhr.response,this.data)}},{key:"isWpNonceError",value:function(){var e=!1,t=!1;return 4==this.xhr.readyState&&(e="object"===_typeof(this.xhr.response)&&null!==this.xhr.response&&this.xhr.response.hasOwnProperty("data")&&this.xhr.response.data.hasOwnProperty("status")&&403===this.xhr.response.data.status,t="-1"===this.xhr.response&&403===this.xhr.status),e||t}},{key:"getFreshNonceAndRerunXHR",value:function(e){var t,n="";e.hasOwnProperty("headers")&&e.headers.hasOwnProperty("X-WP-Nonce")&&(n=e.headers["X-WP-Nonce"]),""!==(n=e.hasOwnProperty("data")&&e.data.hasOwnProperty("_ajax_nonce")?e.data._ajax_nonce:n)&&((t={method:"POST"}).data={spbc_remote_call_action:"get_fresh_wpnonce",plugin_name:"antispam",nonce_prev:n,initial_request_params:e},t.notJson=!0,t.url=ctPublicFunctions.host_url,t.callback=function(){for(var e=arguments.length,t=new Array(e),n=0;n{function o(){for(var e=arguments.length,t=new Array(e),n=0;n{function a(){for(var e=arguments.length,t=new Array(e),n=0;n{return _createClass(function e(){_classCallCheck(this,e),this.config=ApbctFetchProxyConfig},[{key:"findMatchingConfig",value:function(e){for(var t="string"==typeof e?e:null!=e&&"string"==typeof e.href?e.href:"",n=0,o=Object.entries(this.config);nMath.floor((new Date).getTime()/1e3)},isSet:function(e){return null!==localStorage.getItem(e)},delete:function(e){localStorage.removeItem(e)},getCleanTalkData:function(){for(var e={},t=0;t_createClass(function e(){_classCallCheck(this,e)},[{key:"attachEventTokenToMultipageGravityForms",value:function(){document.addEventListener("gform_page_loaded",function(){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||"function"!=typeof setEventTokenField||"function"!=typeof botDetectorLocalStorage||setEventTokenField(botDetectorLocalStorage.get("bot_detector_event_token"))})}},{key:"attachEventTokenToWoocommerceGetRequestAddToCart",value:function(){ctPublic.wc_ajax_add_to_cart||document.querySelectorAll("a.add_to_cart_button:not(.product_type_variable):not(.wc-interactive)").forEach(function(o){o.addEventListener("click",function(e){var t=o.getAttribute("href"),n=apbctLocalStorage.get("bot_detector_event_token");n&&(-1===t.indexOf("?")?t+="?":t+="&",o.setAttribute("href",t+="ct_bot_detector_event_token="+n))})})}},{key:"restartBotDetectorEventTokenAttach",value:function(){var e,t=0_createClass(function e(){_classCallCheck(this,e)},[{key:"attachHiddenFieldsToForms",value:function(e){void 0!==ctPublic.force_alt_cookies&&("undefined"===ctPublic.force_alt_cookies||ctPublic.force_alt_cookies)||+ctPublic.bot_detector_enabled&&!e||(ctNoCookieAttachHiddenFieldsToForms(),document.addEventListener("gform_page_loaded",ctNoCookieAttachHiddenFieldsToForms))}},{key:"attachVisibleFieldsToForm",value:function(e,t){var n=document.createElement("input"),t=(n.setAttribute("type","hidden"),n.setAttribute("id","apbct_visible_fields_"+t),n.setAttribute("name","apbct_visible_fields"),{});t[0]=this.collectVisibleFields(e),n.value=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),e.append(n)}},{key:"attachVisibleFieldsDuringSubmit",value:function(e,t){"native"!==ctPublic.data__cookies_type&&void 0!==e.target.ctFormIndex&&this.setVisibleFieldsCookie(this.collectVisibleFields(t),e.target.ctFormIndex)}},{key:"constructNoCookieHiddenField",value:function(e){var t="hidden",e=("submit"===e&&(t="submit"),""),n=getCleanTalkStorageDataArray(),n=JSON.stringify(n);return n="_ct_no_cookie_data_"+btoa(unescape(encodeURIComponent(n))),(e=document.createElement("input")).setAttribute("name","ct_no_cookie_hidden_field"),e.setAttribute("value",n),e.setAttribute("type",t),e.classList.add("apbct_special_field"),e.classList.add("ct_no_cookie_hidden_field"),e}},{key:"attachNoCookieDuringSubmit",value:function(e){"none"===ctPublic.data__cookies_type&&e.target&&e.target.action&&-1!==e.target.action.toString().indexOf("mailpoet_subscription_form")&&(window.XMLHttpRequest.prototype.send=function(e){var t,n;+ctPublic.bot_detector_enabled?(t=(new ApbctHandler).toolGetEventToken())&&(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+("data%5Bct_bot_detector_event_token%5D="+t+"&")+e)):(n="data%5Bct_no_cookie_hidden_field%5D="+getNoCookieData()+"&",defaultSend.call(this,n+e)),setTimeout(function(){window.XMLHttpRequest.prototype.send=defaultSend},0)})}},{key:"setVisibleFieldsCookie",value:function(e,t){var n="object"===_typeof(e)&&null!==e?e:{};if("native"===ctPublic.data__cookies_type)for(var o in n){if(10{function p(){_classCallCheck(this,p)}return _createClass(p,[{key:"excludeForm",value:function(e){return!!this.checkHiddenFieldsExclusions(e,"visible_fields")||!!(e.querySelector('input[name="wspsc_add_cart_submit"]')||e.querySelector('input[name="option"][value="com_vikrentcar"]')||e.querySelector('input[name="option"][value="com_vikbooking"]'))||void 0!==e.elements.apbct_visible_fields&&0{var n=_asyncToGenerator(_regenerator().m(function e(t,n){var o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(+ctPublic.settings__forms__check_external){e.n=1;break}return e.a(2,!1);case 1:o=_createForOfIteratorHelper(r),e.p=2,o.s();case 3:if((a=o.n()).done)e.n=6;else{if((a=a.value).matches(t,n))return a=a.getForm(),e.n=4,c(a);e.n=5}break;case 4:if(e.v)return e.a(2,!0);e.n=5;break;case 5:e.n=3;break;case 6:e.n=8;break;case 7:e.p=7,a=e.v,o.e(a);case 8:return e.p=8,o.f(),e.f(8);case 9:return e.a(2,!1)}},e,null,[[2,7,8,9]])}));return function(e,t){return n.apply(this,arguments)}})(),r=[{name:"bitrix24",matches:function(e,t){return document.querySelector(".b24-form")&&e.includes("bitrix/services/main/ajax.php?action=crm.site.form.fill")&&t[1].body instanceof FormData},getForm:function(){return document.querySelector(".b24-form form")}},{name:"sender",matches:function(e,t){return e.includes("stats.sender.net/forms")&&"string"==typeof t[1].body},getForm:function(){for(var e=document.querySelectorAll("iframe"),t=0;t{var t=_asyncToGenerator(_regenerator().m(function e(t){var n,o,a;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:if(t){e.n=1;break}return e.a(2,!1);case 1:return n=i(t),m=!0,e.p=2,e.n=3,new Promise(function(e,t){apbct_public_sendAJAX(n,{async:!0,callback:e,onErrorCallback:t})});case 3:return o=e.v,(a=void 0!==o.apbct&&+o.apbct.blocked||void 0!==o.data&&void 0!==o.data.message)&&(new ApbctShowForbidden).parseBlockMessage(o),e.a(2,a);case 4:return e.p=4,e.a(2,!1);case 5:return e.p=5,m=!1,e.f(5);case 6:return e.a(2)}},e,null,[[2,4,5,6]])}));return function(e){return t.apply(this,arguments)}})(),i=function(e){var t,n={action:"cleantalk_force_ajax_check"},o=_createForOfIteratorHelper(e.elements);try{for(o.s();!(t=o.n()).done;){var a=t.value;a.name&&(n[a.name]=a.value)}}catch(e){o.e(e)}finally{o.f()}return+ctPublic.bot_detector_enabled?n.ct_bot_detector_event_token=apbctLocalStorage.get("bot_detector_event_token"):n.ct_no_cookie_hidden_field=getNoCookieData(),n};window.fetch=_asyncToGenerator(_regenerator().m(function e(){var t,n,o,a,r,c,i,l,s,u,d,p=arguments;return _regenerator().w(function(e){for(;;)switch(e.p=e.n){case 0:for(t=p.length,n=new Array(t),o=0;o!(!t||"string"!=typeof t)&&["google.com/recaptcha","gstatic.com/recaptcha","recaptcha.google.com","recaptcha.net","www.google.com/recaptcha","apis.google.com","paypal.com","api.paypal.com","www.paypal.com","js.stripe.com","api.stripe.com","checkout.stripe.com","api.doboard.com"].some(function(e){return t.includes(e)}))(a="string"==typeof n[0]?n[0]:(null==(a=n[0])?void 0:a.url)||""))return e.a(2,h.apply(this,n));e.n=2;break;case 2:if(n&&n[0]&&n[1]&&n[1].body){e.n=3;break}return e.a(2,h.apply(this,n));case 3:return e.n=4,b.processFetch(n);case 4:if(!0===e.v)return e.a(2,Promise.reject(new Error("Forbidden")));e.n=5;break;case 5:if(0{try{return n[0].includes(new URL(ctPublicFunctions._rest_url).pathname+"metform/")}catch(e){}})()))try{n[1].body=f(n[1].body,_(+ctPublic.bot_detector_enabled))}catch(e){}if(0{var t=e.value;"undefined"!=typeof ctPublic&&1==+ctPublic.settings__forms__search_test&&null!==t.getAttribute("apbct-form-sign")&&"native_search"===t.getAttribute("apbct-form-sign")&&(t.apbctSearchPrevOnsubmit=t.onsubmit,t.onsubmit=function(e){return n.searchFormHandler(e,t)})})()}catch(e){t.e(e)}finally{t.f()}}},{key:"searchFormHandler",value:function(e,t){try{var n,o,a,r=t.querySelector('[name*="apbct__email_id__"]'),c=null,i=(null!==r&&null!==r.value&&(c=r.value),getCleanTalkStorageDataArray()),l=apbctLocalStorage.get("bot_detector_event_token");null===i&&null===r&&null===l||(e.preventDefault(),n=function(){null!==r&&r.parentNode.removeChild(r),"function"==typeof t.apbctSearchPrevOnsubmit?t.apbctSearchPrevOnsubmit():HTMLFormElement.prototype.submit.call(t)},o=i,null!==c&&(o.apbct_search_form__honeypot_value=c),o.ct_bot_detector_event_token=l,"string"==typeof o.apbct_pixel_url&&-1!==o.apbct_pixel_url.indexOf("%3A")&&(o.apbct_pixel_url=decodeURIComponent(o.apbct_pixel_url)),void 0!==(a=JSON.stringify(o))&&0!==a.length?ctSetAlternativeCookie(a,{callback:n,onErrorCallback:n,forceAltCookies:!0}):n())}catch(e){console.warn("APBCT search form onsubmit handler error. "+e)}}},{key:"toolForAntiCrawlerCheckDuringBotDetector",value:function(){var e=setInterval(function(){localStorage.bot_detector_event_token&&(ctSetCookie("apbct_bot_detector_exist","1","3600"),clearInterval(e))},500)}},{key:"toolGetEventToken",value:function(){var t=localStorage.getItem("bot_detector_event_token");try{t=JSON.parse(t)}catch(e){t=!1}return!(null===t||!1===t||!t.hasOwnProperty("value")||""===t.value)&&t.value}}])})(),ApbctShowForbidden=(()=>_createClass(function e(){_classCallCheck(this,e)},[{key:"prepareBlockForAjaxForms",value:function(){var o=function(e){if(e.responseText&&-1!==e.responseText.indexOf('"apbct')&&-1===e.responseText.indexOf("DOCTYPE"))try{this.parseBlockMessage(JSON.parse(e.responseText))}catch(e){console.log(e.toString())}}.bind(this);"undefined"!=typeof jQuery?"function"!=typeof jQuery(document).ajaxComplete()?jQuery(document).on("ajaxComplete",function(e,t,n){o(t)}):jQuery(document).ajaxComplete(function(e,t,n){o(t)}):"undefined"!=typeof XMLHttpRequest&&document.addEventListener("readystatechange",function(e){4===e.target.readyState&&o(e.target)})}},{key:"parseBlockMessage",value:function(e){var t,n="";if((void 0!==e.apbct&&(e=e.apbct).blocked&&(n=e.comment),n=void 0!==e.data&&void 0!==(e=e.data).message?e.message:n)&&(document.dispatchEvent(new CustomEvent("apbctAjaxBockAlert",{bubbles:!0,detail:{message:n}})),cleantalkModal.loaded=n,cleantalkModal.open(),1==+e.stop_script&&(window.stop(),e.integration&&"NEXForms"===e.integration&&((t=document.querySelector("form.submit-nex-form button.nex-submit"))&&(t.disabled=!0,t.style.opacity="0.5",t.style.cursor="not-allowed",t.style.pointerEvents="none",t.style.backgroundColor="#ccc",t.style.color="#fff"),t=document.querySelector("div.nex_success_message"))&&(t.style.display="none"),e.integration)&&"ElfsightForm"===e.integration)){var o=[document];try{document.querySelectorAll("iframe").forEach(function(e){try{e.contentDocument&&o.push(e.contentDocument)}catch(e){}})}catch(e){}for(var a=0,r=o;a_createClass(function e(){_classCallCheck(this,e)},[{key:"extract",value:function(e){if(e&&"string"==typeof e){try{e=decodeURIComponent(e)}catch(e){return!1}var t=document.querySelectorAll("form"),n=this.getIdFromAjax(e);if(n){var o,a=_createForOfIteratorHelper(t);try{for(a.s();!(o=a.n()).done;){var r=o.value,c=this.findParentContainer(r);if(c){var i=this.getIdFromHTML(c);if(i===n){var l=c.querySelector("input[id^=apbct_visible_fields_]");if(null!=l&&l.value)return l.value}}}}catch(e){a.e(e)}finally{a.f()}}}return!1}},{key:"getIdFromAjax",value:function(e){return console.warn("getIdFromAjax must be implemented by child class"),null}},{key:"findParentContainer",value:function(e){return console.warn("findParentContainer must be implemented by child class"),null}},{key:"getIdFromHTML",value:function(e){return console.warn("getIdFromHTML must be implemented by child class"),null}}],[{key:"createExtractor",value:function(e){switch(e){case"action=nf_ajax_submit":return new ApbctNinjaFormsVisibleFields;case"action=mailpoet":return new ApbctMailpoetVisibleFields;default:return null}}}]))(),ApbctNinjaFormsVisibleFields=(()=>{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/"id"\s*:\s*"?(\d+)"/,/form_id\s*[:\s]*"?(\d+)"/,/nf-form-(\d+)/,/"id":(\d+)/];t{function e(){return _classCallCheck(this,e),_callSuper(this,e,arguments)}return _inherits(e,ApbctVisibleFieldsExtractor),_createClass(e,[{key:"getIdFromAjax",value:function(e){for(var t=0,n=[/form_id\s*[:\s]*"?(\d+)"/,/data\[form_id\]=(\d+)/,/form_id=(\d+)/];t_createClass(function e(){_classCallCheck(this,e)},[{key:"setSessionId",value:function(){var e;apbctSessionStorage.isSet("apbct_session_id")?apbctLocalStorage.set("apbct_page_hits",Number(apbctLocalStorage.get("apbct_page_hits"))+1):(e=Math.random().toString(36).replace(/[^a-z]+/g,"").substr(2,10),apbctSessionStorage.set("apbct_session_id",e,!1),apbctLocalStorage.set("apbct_page_hits",1),document.referrer&&new URL(document.referrer).host!==location.host&&apbctSessionStorage.set("apbct_site_referer",document.referrer,!1))}},{key:"writeReferrersToSessionStorage",value:function(){var e=apbctSessionStorage.get("apbct_session_current_page");!1!==e&&document.location.href!==e&&apbctSessionStorage.set("apbct_prev_referer",e,!1),apbctSessionStorage.set("apbct_session_current_page",document.location.href,!1)}},{key:"setCookiesType",value:function(){var e=apbctLocalStorage.get("ct_cookies_type");e&&e===ctPublic.data__cookies_type||(apbctLocalStorage.set("ct_cookies_type",ctPublic.data__cookies_type),apbctLocalStorage.delete("ct_mouse_moved"),apbctLocalStorage.delete("ct_has_scrolled"))}},{key:"startFieldsListening",value:function(){if(!apbctLocalStorage.isSet("ct_has_key_up")&&!apbctLocalStorage.get("ct_has_key_up")||!apbctLocalStorage.isSet("ct_has_input_focused")&&!apbctLocalStorage.get("ct_has_input_focused")||"native"!==ctPublic.data__cookies_type||void 0===ctGetCookie("ct_has_input_focused")||void 0===ctGetCookie("ct_has_key_up")){var e=ctGetPageForms();if(ctPublic.handled_fields=[],0_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"elementBody",document.querySelector("body")),_defineProperty(this,"collectionForms",document.forms),this.setListeners()},[{key:"setListeners",value:function(){var t=this;this.elementBody.addEventListener("click",function(e){t.checkElementInForms(e,"addClicks")}),this.elementBody.addEventListener("mouseup",function(e){"Range"==document.getSelection().type.toString()&&t.addSelected()}),this.elementBody.addEventListener("mousemove",function(e){t.checkElementInForms(e,"trackMouseMovement")})}},{key:"checkElementInForms",value:function(e,t){for(var n,o=0;o_createClass(function e(){_classCallCheck(this,e),_defineProperty(this,"fieldData",{isAutoFill:!1,isUseBuffer:!1,speedDelta:0,firstKeyTimestamp:0,lastKeyTimestamp:0,lastDelta:0,countOfKey:0}),_defineProperty(this,"fields",document.querySelectorAll("textarea[name=comment]")),_defineProperty(this,"data",[])},[{key:"gatheringFields",value:function(){var n=this;Array.prototype.slice.call(this.fields).forEach(function(e,t){n.data.push(Object.assign({},n.fieldData))})}},{key:"setListeners",value:function(){var o=this;this.fields.forEach(function(e,t){e.addEventListener("paste",function(){o.data[t].isUseBuffer=!0})}),this.fields.forEach(function(e,t){e.addEventListener("onautocomplete",function(){o.data[t].isAutoFill=!0})}),this.fields.forEach(function(e,n){e.addEventListener("input",function(){o.data[n].countOfKey++;var e,t=+new Date;1===o.data[n].countOfKey?(o.data[n].lastKeyTimestamp=t,o.data[n].firstKeyTimestamp=t):(e=t-o.data[n].lastKeyTimestamp,2===o.data[n].countOfKey?(o.data[n].lastKeyTimestamp=t,o.data[n].lastDelta=e):2{function o(){_classCallCheck(this,o)}return _createClass(o,null,[{key:"getFrontendDataLog",value:function(){var e=("undefined"!=typeof ctPublicFunctions&&ctPublicFunctions.cookiePrefix?ctPublicFunctions.cookiePrefix:"")+o.LOG_KEY,t=o.LOG_KEY;if(void 0!==apbctLocalStorage&&apbctLocalStorage.get){var n=apbctLocalStorage.get(e)||apbctLocalStorage.get(t)||null;if(n&&"string"==typeof n)try{return JSON.parse(n)}catch(e){return""}return n}n=(n=localStorage.getItem(e))||localStorage.getItem(t)||null;try{return"string"==typeof n?JSON.parse(n):n}catch(e){return""}}},{key:"asDTO",value:function(){return{botd_logic_loaded:o.botdLogicLoaded,botd_wrapper_loaded:o.botdWrapperLoaded,frontend_data_log:"",transport_enabled:1}}},{key:"detectScripts",value:function(){if(o.botdWrapperLoaded&&o.botdLogicLoaded)return!0;for(var e=document.getElementsByTagName("script"),t=0;t .comment-body *[class*="comment-author"]',document.querySelector(".apbct-trp .comment-author .comment-author-link")&&(e='.apbct-trp *[class*="comment-author-link"]'),0!==(e=document.querySelectorAll(e+',.apbct-trp > .wp-block-group *[class*="comment-author"],.apbct-trp *[class*="review__author"],.apbct-trp td[class*="column-author"] > strong')).length)&&(e.forEach(function(e,t){var n,o,a,r,c,i,l,s,u;e.className.indexOf("review")<0&&"undefined"==typeof pagenow&&e.parentElement.className.indexOf("group")<0&&"DIV"!=e.tagName||e.querySelector(".comment-metadata")||((n=document.createElement("div")).setAttribute("class","apbct-real-user-badge"),(o=document.createElement("img")).setAttribute("src",d.imgPersonUrl),o.setAttribute("class","apbct-real-user-popup-img"),(a=document.createElement("div")).setAttribute("class","apbct-real-user-popup"),(i=document.createElement("strong")).append(d.phrases.trpHeading),(r=document.createElement("div")).setAttribute("class","apbct-real-user-popup-content_row"),(c=document.createElement("div")).append(" "),c.append(i),c.append(d.phrases.trpContent1),(i=document.createElement("div")).style.display="flex",i.style.gap="5px",(l=document.createElement("div")).append(d.phrases.trpContent2),i.append(l),p&&(l=document.createElement("div"),(s=document.createElement("a")).setAttribute("href",d.trpContentLink),s.setAttribute("target","_blank"),(u=document.createElement("img")).setAttribute("src",ctAdminCommon.new_window_gif),u.setAttribute("alt","New window"),u.setAttribute("style","padding-top:3px"),s.append(u),l.append(s),i.append(l)),r.append(c,i),a.append(r),n.append(o),e.append(n),e.append(a))}),document.querySelectorAll(".apbct-real-user-badge").forEach(function(o){var a=void 0,e=(t.body.addEventListener("click",function(e){-1==e.target.className.indexOf("apbct-real-user")&&-1==e.target.parentElement.className.indexOf("apbct-real-user")&&closeAllPopupTRP()}),o.addEventListener("click",function(){var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.toggle("visible")}),o.addEventListener("mouseenter",function(){closeAllPopupTRP();var e=this.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.add("visible")}),o.addEventListener("mouseleave",function(){var t=this;a=setTimeout(function(){var e=t.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.nextElementSibling);e.addEventListener("mouseenter",function(){clearTimeout(a),e.classList.add("visible")}),e.addEventListener("mouseleave",function(){a=setTimeout(function(){e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},1e3)}),o.addEventListener("touchend",function(){var n=this;a=setTimeout(function(){var e=n.nextElementSibling,t=window.getSelection();e&&t&&e.classList.contains("apbct-real-user-popup")&&0===t.toString().length?e.classList.remove("visible"):(clearTimeout(a),document.addEventListener("selectionchange",function e(){var t=window.getSelection();t&&0===t.toString().length&&(a=setTimeout(function(){var e=o.nextElementSibling;e&&e.classList.contains("apbct-real-user-popup")&&e.classList.remove("visible")},3e3),document.removeEventListener("selectionchange",e))}))},3e3)})}))}); \ No newline at end of file diff --git a/js/cleantalk-admin-settings-page.min.js b/js/cleantalk-admin-settings-page.min.js index f8bd99837..012ff03aa 100644 --- a/js/cleantalk-admin-settings-page.min.js +++ b/js/cleantalk-admin-settings-page.min.js @@ -1,2 +1,2 @@ -let __=wp.i18n.__;function handleAnchorDetection(t){"none"===document.querySelector("#apbct_settings__advanced_settings").style.display&&apbctExceptedShowHide("apbct_settings__advanced_settings"),scrollToAnchor("#"+t)}function scrollToAnchor(t){t=document.querySelector(t);t&&t.scrollIntoView({block:"end"})}function apbctManageEmailEncoderCustomTextField(){var t=document.querySelector("#apbct_setting_data__email_decoder_obfuscation_custom_text");let e;null!==t&&(e=void 0!==t.parentElement?t.parentElement:null),document.querySelectorAll(".apbct_setting---data__email_decoder_obfuscation_mode").forEach(t=>{e&&t.checked&&"replace"!==t.value&&e.classList.add("hidden"),t.addEventListener("click",t=>{void 0!==e&&("replace"===t.target.value?e.classList.remove("hidden"):e.classList.add("hidden"))})})}function apbctManageAntiCrawlerDependency(){let e=document.querySelector("#apbct_setting_sfw__anti_crawler"),n=document.querySelector("#apbct_setting_sfw__enabled");e&&n&&e.addEventListener("change",()=>{var t;e.checked&&!n.checked&&(n.checked=!0,null!==(t=n.getAttribute("apbct_children")))&&apbctSettingsDependencies(t,1)})}function apbctBannerCheck(){let c=setInterval(function(){apbct_admin_sendAJAX({action:"apbct_settings__check_renew_banner"},{callback:function(t,e,n,a){t.close_renew_banner&&(jQuery("#cleantalk_notice_renew").length&&jQuery("#cleantalk_notice_renew").hide("slow"),jQuery("#cleantalk_notice_trial").length&&jQuery("#cleantalk_notice_trial").hide("slow"),clearInterval(c))}})},9e5)}function apbctGetElems(a){for(let t=0,e=(a=a.split(",")).length,n;t{document.getElementById(t)&&"none"!==document.getElementById(t).style.display&&apbctShowHideElem(t)})}function apbctShowRequiredGroups(t,e){var n=document.getElementById("apbct_settings__dwpms_settings");n&&"none"===n.style.display&&((n=t).preventDefault(),apbctShowHideElem("apbct_settings__dwpms_settings"),document.getElementById(e).dispatchEvent(new n.constructor(n.type,n)))}function apbctSettingsDependencies(t,c){c=isNaN(c)?null:c,apbctGetElemsNative(t).forEach(function(t,e,n){var a;1===(c=null===c?null===t.getAttribute("disabled")?0:1:c)?t.removeAttribute("disabled"):t.setAttribute("disabled","disabled"),null!==t.getAttribute("apbct_children")&&null!==(a=apbctSettingsDependenciesGetState(t)&&c)&&apbctSettingsDependencies(t.getAttribute("apbct_children"),a)})}function apbctSettingsDependenciesGetState(t){let e;switch(t.getAttribute("type")){case"checkbox":e=+t.checked;break;case"radio":e=+(1==+t.getAttribute("value"));break;default:e=null}return e}function onApbctCookieTypeChange(t){t=t?.target?.value?.toString()||null;null===t||"1"!==t&&"0"!==t||(cleantalkModal.loaded=!1,cleantalkModal.open(!1),cleantalkModal.confirm(__("Attention!","cleantalk-spam-protect"),__("Cache solutions detected. ","cleantalk-spam-protect")+__("Switching cookie mode to 'On' or 'Off' may affect filtering quality. ","cleantalk-spam-protect")+__("The recommended setting is 'Auto'.","cleantalk-spam-protect"),"",t=>{!0===t&&jQuery("#apbct_setting_data__set_cookies__Auto").click()},__('Set to "Auto"',"cleantalk-spam-protect"),__("Confirm mode change","cleantalk-spam-protect")))}function apbctSettingsShowDescription(t,e){function c(t){var e=0!=jQuery(t.target).parent(".apbct_long_desc").length,t=jQuery(t.target).hasClass("apbct_long_desc__cancel");(0
");var n=jQuery("#apbct_long_desc__"+e);n.append("").append("
").css({top:t.position().top-5,left:t.position().left+25}),apbct_admin_sendAJAX({action:"apbct_settings__get__long_description",setting_id:e},{spinner:n.children("img"),callback:function(t,e,n,a){t&&t.title&&t.desc&&(a.empty().append("
").append("").append("

"+t.title+"

").append("

"+t.desc+"

"),jQuery(document).on("click",c))}},n)}function apbctNavigationMenuPosition(){var t,e,n=document.querySelector("#apbct_hidden_section_nav ul"),a=document.querySelector("#apbct_settings__button_section");n&&a&&(t=window.scrollY,e=window.innerWidth,1e3"+t.data+"

").insertAfter(jQuery(c)),jQuery("#apbct_settings_templates_import_button .apbct_success").show(300),setTimeout(function(){jQuery("#apbct_settings_templates_import_button .apbct_success").hide(300)},2e3),document.addEventListener("cleantalkModalClosed",function(t){document.location.reload()}),setTimeout(function(){cleantalkModal.close()},2e3)):jQuery("

"+t.data+"

").insertAfter(jQuery(c))}})}}),jQuery(document).on("click","#apbct_settings_templates_export_button",function(){jQuery("#apbct-ajax-result").remove();var t=jQuery("option:selected",jQuery("#apbct_settings_templates_export")),e=jQuery("#apbct_settings_templates_export_name");let n={};if(e.css("border-color","inherit"),void 0===t.data("id"))console.log('Attribute "data-id" not set for the option.');else{if("new_template"===t.data("id")){var a=e.val();if(""===a)return void e.css("border-color","red");n={template_name:a}}else n={template_id:t.data("id")};let c=this;apbct_admin_sendAJAX({action:"settings_templates_export",data:n},{timeout:25e3,button:c,spinner:jQuery("#apbct_settings_templates_export_button .apbct_preloader_button"),notJson:!0,callback:function(t,e,n,a){t.success?(jQuery("

"+t.data+"

").insertAfter(jQuery(c)),jQuery("#apbct_settings_templates_export_button .apbct_success").show(300),setTimeout(function(){jQuery("#apbct_settings_templates_export_button .apbct_success").hide(300)},2e3),document.addEventListener("cleantalkModalClosed",function(t){document.location.reload()}),setTimeout(function(){cleantalkModal.close()},2e3)):jQuery("

"+t.data+"

").insertAfter(jQuery(c))}})}}),jQuery(document).on("click","#apbct_settings_templates_reset_button",function(){let c=this;apbct_admin_sendAJAX({action:"settings_templates_reset"},{timeout:25e3,button:c,spinner:jQuery("#apbct_settings_templates_reset_button .apbct_preloader_button"),notJson:!0,callback:function(t,e,n,a){t.success?(jQuery("

"+t.data+"

").insertAfter(jQuery(c)),jQuery("#apbct_settings_templates_reset_button .apbct_success").show(300),setTimeout(function(){jQuery("#apbct_settings_templates_reset_button .apbct_success").hide(300)},2e3),document.addEventListener("cleantalkModalClosed",function(t){document.location.reload()}),setTimeout(function(){cleantalkModal.close()},2e3)):jQuery("

"+t.data+"

").insertAfter(jQuery(c))}})}),jQuery("#apbct_button__sync").on("click",function(){apbct_admin_sendAJAX({action:"apbct_sync"},{timeout:25e3,button:document.getElementById("apbct_button__sync"),spinner:jQuery("#apbct_button__sync .apbct_preloader_button"),callback:function(t,e,n,a){jQuery("#apbct_button__sync .apbct_success").show(300),setTimeout(function(){jQuery("#apbct_button__sync .apbct_success").hide(300)},2e3),t.reload&&(ctSettingsPage.key_changed?(jQuery(".key_changed_sync").hide(300),jQuery(".key_changed_success").show(300),setTimeout(function(){document.location.reload()},3e3)):document.location.reload())}})}),ctSettingsPage.key_changed&&jQuery("#apbct_button__sync").click(),jQuery(document).on("click",".apbct_settings-long_description---show",function(){apbctSettingsShowDescription(self=jQuery(this),self.attr("setting"))}),(jQuery("#cleantalk_notice_renew").length||jQuery("#cleantalk_notice_trial").length)&&apbctBannerCheck(),jQuery(document).on("change","#apbct_settings_templates_export",function(){"new_template"===jQuery("option:selected",this).data("id")?jQuery(this).parent().parent().find("#apbct_settings_templates_export_name").show():jQuery(this).parent().parent().find("#apbct_settings_templates_export_name").hide()}),apbctSaveButtonPosition();let t;window.addEventListener("scroll",function(){clearTimeout(t),t=setTimeout(function(){apbctSaveButtonPosition()},50),apbctNavigationMenuPosition()}),jQuery("#ct_adv_showhide a").on("click",apbctSaveButtonPosition),jQuery("#apbct-change-account-email").on("click",function(t){t.preventDefault();var t=jQuery(this),e=jQuery("#apbct-account-email"),n=e.text();t.toggleClass("active"),t.hasClass("active")?(t.text(t.data("save-text")),e.attr("contenteditable","true"),e.on("keydown",function(t){"Enter"===t.code&&t.preventDefault()}),e.on("input",function(t){"insertParagraph"===t.inputType&&t.preventDefault()})):(apbct_admin_sendAJAX({action:"apbct_update_account_email",accountEmail:n},{timeout:5e3,callback:function(t,e,n,a){void 0!==t.error&&jQuery("#apbct-account-email").css("border-color","red")}}),e.attr("contenteditable","false"),t.text(t.data("default-text")))}),jQuery("#apbct_setting_apikey").on("input",function(){var t=jQuery(this).val(),e=(jQuery("#apbct_settings__key_line__save_settings").off("click"),""!==t&&null===t.match(/^[a-z\d]{8,30}\s*$/));jQuery("#apbct_settings__key_is_bad").hide(),jQuery("#apbct_showApiKey").hide(),jQuery("#apbct_settings__account_name_ob").hide(),""===t?(jQuery("#apbct_button__key_line__save_changes_wrapper").hide(),jQuery("#apbct_button__get_key_auto").length&&jQuery("#apbct_button__get_key_auto__wrapper").show()):(jQuery("#apbct_button__key_line__save_changes_wrapper").show(),jQuery("#apbct_button__get_key_auto__wrapper").hide(),e&&jQuery("#apbct_settings__key_line__save_settings").on("click",function(t){t.preventDefault(),jQuery("#apbct_settings__key_is_bad").show(),apbctHighlightElement("apbct_setting_apikey",3)}))}),jQuery("#apbct_setting_apikey").val()&&ctSettingsPage.key_is_ok&&jQuery("#apbct_button__get_key_auto__wrapper").hide(),ctSettingsPage.key_is_ok||ctSettingsPage.ip_license||jQuery('button.cleantalk_link[value="save_changes"]').on("click",function(t){t.preventDefault(),jQuery("#sync_required_notice").length||jQuery("

Synchronization process failed. Please, check the acces key and restart the synch.

").insertAfter(jQuery("#apbct_button__sync")),apbctHighlightElement("apbct_setting_apikey",3),apbctHighlightElement("apbct_button__sync",3),jQuery("#apbct_button__get_key_auto__wrapper").show()}),jQuery("#apbct-custom-logo-open-gallery").click(function(t){t.preventDefault();let e=jQuery(this),n=wp.media({library:{type:"image"},multiple:!1});n.on("select",function(){var t=n.state().get("selection").first().toJSON();e.parent().prev().attr("src",t.url),jQuery("#cleantalk_custom_logo").val(t.id)}),n.open()}),jQuery("#apbct-custom-logo-remove-image").click(function(t){t.preventDefault(),!0===confirm("Sure?")&&(t=jQuery(this).parent().prev().data("src"),jQuery(this).parent().prev().attr("src",t),jQuery(this).prev().prev().val(""))}),jQuery('button[id*="apbct-action-adjust-change-"]').click(function(t){t.preventDefault();var t={action:"apbct_action_adjust_change"},e=(t.adjust=jQuery(this).data("adjust"),{});e.button=document.getElementById("apbct-action-adjust-change-"+t.adjust),e.notJson=!0,e.callback=function(){document.location.reload()},apbct_admin_sendAJAX(t,e)}),jQuery('button[id*="apbct-action-adjust-reverse-"]').click(function(t){t.preventDefault();var t={action:"apbct_action_adjust_reverse"},e=(t.adjust=jQuery(this).data("adjust"),{});e.button=document.getElementById("apbct-action-adjust-reverse-"+t.adjust),e.notJson=!0,e.callback=function(){document.location.reload()},apbct_admin_sendAJAX(t,e)}),document.querySelector(".apbct_hidden_section_nav_mob_btn")?.addEventListener("click",()=>{document.querySelector("#apbct_hidden_section_nav ul").style.display="block",document.querySelector(".apbct_hidden_section_nav_mob_btn").style.display="none"}),document.querySelector(".apbct_hidden_section_nav_mob_btn-close")?.addEventListener("click",()=>{document.querySelector("#apbct_hidden_section_nav ul").style.display="none",document.querySelector(".apbct_hidden_section_nav_mob_btn").style.display="block"}),apbctManageEmailEncoderCustomTextField(),apbctManageAntiCrawlerDependency(),window.location.hash&&handleAnchorDetection(window.location.hash.substring(1)),jQuery("body").on("click",".apbct-trial-renew-fullpage .notice-dismiss",function(t){t.preventDefault(),sessionStorage.setItem("apbct_trial_fullpage_dismissed","1"),jQuery(".apbct-trial-renew-fullpage").hide(),jQuery("#apbct-settings-page-wrap").show()})}); +let __=wp.i18n.__;function handleAnchorDetection(t){"none"===document.querySelector("#apbct_settings__advanced_settings").style.display&&apbctExceptedShowHide("apbct_settings__advanced_settings"),scrollToAnchor("#"+t)}function scrollToAnchor(t){t=document.querySelector(t);t&&t.scrollIntoView({block:"end"})}function apbctManageEmailEncoderCustomTextField(){var t=document.querySelector("#apbct_setting_data__email_decoder_obfuscation_custom_text");let e;null!==t&&(e=void 0!==t.parentElement?t.parentElement:null),document.querySelectorAll(".apbct_setting---data__email_decoder_obfuscation_mode").forEach(t=>{e&&t.checked&&"replace"!==t.value&&e.classList.add("hidden"),t.addEventListener("click",t=>{void 0!==e&&("replace"===t.target.value?e.classList.remove("hidden"):e.classList.add("hidden"))})})}function apbctManageAntiCrawlerDependency(){let e=document.querySelector("#apbct_setting_sfw__anti_crawler"),n=document.querySelector("#apbct_setting_sfw__enabled");e&&n&&e.addEventListener("change",()=>{var t;e.checked&&!n.checked&&(n.checked=!0,null!==(t=n.getAttribute("apbct_children")))&&apbctSettingsDependencies(t,1)})}function apbctBannerCheck(){let c=setInterval(function(){apbct_admin_sendAJAX({action:"apbct_settings__check_renew_banner"},{callback:function(t,e,n,a){t.close_renew_banner&&(jQuery("#cleantalk_notice_renew").length&&jQuery("#cleantalk_notice_renew").hide("slow"),jQuery("#cleantalk_notice_trial").length&&jQuery("#cleantalk_notice_trial").hide("slow"),clearInterval(c))}})},9e5)}function apbctGetElems(a){for(let t=0,e=(a=a.split(",")).length,n;t{document.getElementById(t)&&"none"!==document.getElementById(t).style.display&&apbctShowHideElem(t)})}function apbctShowRequiredGroups(t,e){var n=document.getElementById("apbct_settings__dwpms_settings");n&&"none"===n.style.display&&((n=t).preventDefault(),apbctShowHideElem("apbct_settings__dwpms_settings"),document.getElementById(e).dispatchEvent(new n.constructor(n.type,n)))}function apbctSettingsDependencies(t,c){c=isNaN(c)?null:c,apbctGetElemsNative(t).forEach(function(t,e,n){var a;1===(c=null===c?null===t.getAttribute("disabled")?0:1:c)?t.removeAttribute("disabled"):t.setAttribute("disabled","disabled"),null!==t.getAttribute("apbct_children")&&null!==(a=apbctSettingsDependenciesGetState(t)&&c)&&apbctSettingsDependencies(t.getAttribute("apbct_children"),a)})}function apbctSettingsDependenciesGetState(t){let e;switch(t.getAttribute("type")){case"checkbox":e=+t.checked;break;case"radio":e=+(1==+t.getAttribute("value"));break;default:e=null}return e}function onApbctCookieTypeChange(t){t=t?.target?.value?.toString()||null;null===t||"1"!==t&&"0"!==t||(cleantalkModal.loaded=!1,cleantalkModal.open(!1),cleantalkModal.confirm(__("Attention!","cleantalk-spam-protect"),__("Cache-problem solutions detected in the environment. ","cleantalk-spam-protect")+__("Switching cookie mode to 'On' or 'Off' may affect filtering quality. ","cleantalk-spam-protect")+__("The recommended setting is 'Auto'.","cleantalk-spam-protect"),"",t=>{!0===t&&jQuery("#apbct_setting_data__set_cookies__Auto").click()},__('Set to "Auto"',"cleantalk-spam-protect"),__("Confirm mode change","cleantalk-spam-protect")))}function apbctSettingsShowDescription(t,e){function c(t){var e=0!=jQuery(t.target).parent(".apbct_long_desc").length,t=jQuery(t.target).hasClass("apbct_long_desc__cancel");(0
");var n=jQuery("#apbct_long_desc__"+e);n.append("").append("
").css({top:t.position().top-5,left:t.position().left+25}),apbct_admin_sendAJAX({action:"apbct_settings__get__long_description",setting_id:e},{spinner:n.children("img"),callback:function(t,e,n,a){t&&t.title&&t.desc&&(a.empty().append("
").append("").append("

"+t.title+"

").append("

"+t.desc+"

"),jQuery(document).on("click",c))}},n)}function apbctNavigationMenuPosition(){var t,e,n=document.querySelector("#apbct_hidden_section_nav ul"),a=document.querySelector("#apbct_settings__button_section");n&&a&&(t=window.scrollY,e=window.innerWidth,1e3"+t.data+"

").insertAfter(jQuery(c)),jQuery("#apbct_settings_templates_import_button .apbct_success").show(300),setTimeout(function(){jQuery("#apbct_settings_templates_import_button .apbct_success").hide(300)},2e3),document.addEventListener("cleantalkModalClosed",function(t){document.location.reload()}),setTimeout(function(){cleantalkModal.close()},2e3)):jQuery("

"+t.data+"

").insertAfter(jQuery(c))}})}}),jQuery(document).on("click","#apbct_settings_templates_export_button",function(){jQuery("#apbct-ajax-result").remove();var t=jQuery("option:selected",jQuery("#apbct_settings_templates_export")),e=jQuery("#apbct_settings_templates_export_name");let n={};if(e.css("border-color","inherit"),void 0===t.data("id"))console.log('Attribute "data-id" not set for the option.');else{if("new_template"===t.data("id")){var a=e.val();if(""===a)return void e.css("border-color","red");n={template_name:a}}else n={template_id:t.data("id")};let c=this;apbct_admin_sendAJAX({action:"settings_templates_export",data:n},{timeout:25e3,button:c,spinner:jQuery("#apbct_settings_templates_export_button .apbct_preloader_button"),notJson:!0,callback:function(t,e,n,a){t.success?(jQuery("

"+t.data+"

").insertAfter(jQuery(c)),jQuery("#apbct_settings_templates_export_button .apbct_success").show(300),setTimeout(function(){jQuery("#apbct_settings_templates_export_button .apbct_success").hide(300)},2e3),document.addEventListener("cleantalkModalClosed",function(t){document.location.reload()}),setTimeout(function(){cleantalkModal.close()},2e3)):jQuery("

"+t.data+"

").insertAfter(jQuery(c))}})}}),jQuery(document).on("click","#apbct_settings_templates_reset_button",function(){let c=this;apbct_admin_sendAJAX({action:"settings_templates_reset"},{timeout:25e3,button:c,spinner:jQuery("#apbct_settings_templates_reset_button .apbct_preloader_button"),notJson:!0,callback:function(t,e,n,a){t.success?(jQuery("

"+t.data+"

").insertAfter(jQuery(c)),jQuery("#apbct_settings_templates_reset_button .apbct_success").show(300),setTimeout(function(){jQuery("#apbct_settings_templates_reset_button .apbct_success").hide(300)},2e3),document.addEventListener("cleantalkModalClosed",function(t){document.location.reload()}),setTimeout(function(){cleantalkModal.close()},2e3)):jQuery("

"+t.data+"

").insertAfter(jQuery(c))}})}),jQuery("#apbct_button__sync").on("click",function(){apbct_admin_sendAJAX({action:"apbct_sync"},{timeout:25e3,button:document.getElementById("apbct_button__sync"),spinner:jQuery("#apbct_button__sync .apbct_preloader_button"),callback:function(t,e,n,a){jQuery("#apbct_button__sync .apbct_success").show(300),setTimeout(function(){jQuery("#apbct_button__sync .apbct_success").hide(300)},2e3),t.reload&&(ctSettingsPage.key_changed?(jQuery(".key_changed_sync").hide(300),jQuery(".key_changed_success").show(300),setTimeout(function(){document.location.reload()},3e3)):document.location.reload())}})}),ctSettingsPage.key_changed&&jQuery("#apbct_button__sync").click(),jQuery(document).on("click",".apbct_settings-long_description---show",function(){apbctSettingsShowDescription(self=jQuery(this),self.attr("setting"))}),(jQuery("#cleantalk_notice_renew").length||jQuery("#cleantalk_notice_trial").length)&&apbctBannerCheck(),jQuery(document).on("change","#apbct_settings_templates_export",function(){"new_template"===jQuery("option:selected",this).data("id")?jQuery(this).parent().parent().find("#apbct_settings_templates_export_name").show():jQuery(this).parent().parent().find("#apbct_settings_templates_export_name").hide()}),apbctSaveButtonPosition();let t;window.addEventListener("scroll",function(){clearTimeout(t),t=setTimeout(function(){apbctSaveButtonPosition()},50),apbctNavigationMenuPosition()}),jQuery("#ct_adv_showhide a").on("click",apbctSaveButtonPosition),jQuery("#apbct-change-account-email").on("click",function(t){t.preventDefault();var t=jQuery(this),e=jQuery("#apbct-account-email"),n=e.text();t.toggleClass("active"),t.hasClass("active")?(t.text(t.data("save-text")),e.attr("contenteditable","true"),e.on("keydown",function(t){"Enter"===t.code&&t.preventDefault()}),e.on("input",function(t){"insertParagraph"===t.inputType&&t.preventDefault()})):(apbct_admin_sendAJAX({action:"apbct_update_account_email",accountEmail:n},{timeout:5e3,callback:function(t,e,n,a){void 0!==t.error&&jQuery("#apbct-account-email").css("border-color","red")}}),e.attr("contenteditable","false"),t.text(t.data("default-text")))}),jQuery("#apbct_setting_apikey").on("input",function(){var t=jQuery(this).val(),e=(jQuery("#apbct_settings__key_line__save_settings").off("click"),""!==t&&null===t.match(/^[a-z\d]{8,30}\s*$/));jQuery("#apbct_settings__key_is_bad").hide(),jQuery("#apbct_showApiKey").hide(),jQuery("#apbct_settings__account_name_ob").hide(),""===t?(jQuery("#apbct_button__key_line__save_changes_wrapper").hide(),jQuery("#apbct_button__get_key_auto").length&&jQuery("#apbct_button__get_key_auto__wrapper").show()):(jQuery("#apbct_button__key_line__save_changes_wrapper").show(),jQuery("#apbct_button__get_key_auto__wrapper").hide(),e&&jQuery("#apbct_settings__key_line__save_settings").on("click",function(t){t.preventDefault(),jQuery("#apbct_settings__key_is_bad").show(),apbctHighlightElement("apbct_setting_apikey",3)}))}),jQuery("#apbct_setting_apikey").val()&&ctSettingsPage.key_is_ok&&jQuery("#apbct_button__get_key_auto__wrapper").hide(),ctSettingsPage.key_is_ok||ctSettingsPage.ip_license||jQuery('button.cleantalk_link[value="save_changes"]').on("click",function(t){t.preventDefault(),jQuery("#sync_required_notice").length||jQuery("

Synchronization process failed. Please, check the acces key and restart the synch.

").insertAfter(jQuery("#apbct_button__sync")),apbctHighlightElement("apbct_setting_apikey",3),apbctHighlightElement("apbct_button__sync",3),jQuery("#apbct_button__get_key_auto__wrapper").show()}),jQuery("#apbct-custom-logo-open-gallery").click(function(t){t.preventDefault();let e=jQuery(this),n=wp.media({library:{type:"image"},multiple:!1});n.on("select",function(){var t=n.state().get("selection").first().toJSON();e.parent().prev().attr("src",t.url),jQuery("#cleantalk_custom_logo").val(t.id)}),n.open()}),jQuery("#apbct-custom-logo-remove-image").click(function(t){t.preventDefault(),!0===confirm("Sure?")&&(t=jQuery(this).parent().prev().data("src"),jQuery(this).parent().prev().attr("src",t),jQuery(this).prev().prev().val(""))}),jQuery('button[id*="apbct-action-adjust-change-"]').click(function(t){t.preventDefault();var t={action:"apbct_action_adjust_change"},e=(t.adjust=jQuery(this).data("adjust"),{});e.button=document.getElementById("apbct-action-adjust-change-"+t.adjust),e.notJson=!0,e.callback=function(){document.location.reload()},apbct_admin_sendAJAX(t,e)}),jQuery('button[id*="apbct-action-adjust-reverse-"]').click(function(t){t.preventDefault();var t={action:"apbct_action_adjust_reverse"},e=(t.adjust=jQuery(this).data("adjust"),{});e.button=document.getElementById("apbct-action-adjust-reverse-"+t.adjust),e.notJson=!0,e.callback=function(){document.location.reload()},apbct_admin_sendAJAX(t,e)}),document.querySelector(".apbct_hidden_section_nav_mob_btn")?.addEventListener("click",()=>{document.querySelector("#apbct_hidden_section_nav ul").style.display="block",document.querySelector(".apbct_hidden_section_nav_mob_btn").style.display="none"}),document.querySelector(".apbct_hidden_section_nav_mob_btn-close")?.addEventListener("click",()=>{document.querySelector("#apbct_hidden_section_nav ul").style.display="none",document.querySelector(".apbct_hidden_section_nav_mob_btn").style.display="block"}),apbctManageEmailEncoderCustomTextField(),apbctManageAntiCrawlerDependency(),window.location.hash&&handleAnchorDetection(window.location.hash.substring(1)),jQuery("body").on("click",".apbct-trial-renew-fullpage .notice-dismiss",function(t){t.preventDefault(),sessionStorage.setItem("apbct_trial_fullpage_dismissed","1"),jQuery(".apbct-trial-renew-fullpage").hide(),jQuery("#apbct-settings-page-wrap").show()})}); //# sourceMappingURL=cleantalk-admin-settings-page.min.js.map diff --git a/js/cleantalk-admin-settings-page.min.js.map b/js/cleantalk-admin-settings-page.min.js.map index 602793fdd..501ab4445 100644 --- a/js/cleantalk-admin-settings-page.min.js.map +++ b/js/cleantalk-admin-settings-page.min.js.map @@ -1 +1 @@ -{"version":3,"file":"cleantalk-admin-settings-page.min.js","sources":["cleantalk-admin-settings-page.js"],"sourcesContent":["const {__} = wp.i18n;\njQuery(document).ready(function() {\n // Crunch for Right to Left direction languages\n if (document.getElementsByClassName('apbct_settings-title')[0]) {\n if (getComputedStyle(document.getElementsByClassName('apbct_settings-title')[0]).direction === 'rtl') {\n jQuery('.apbct_switchers').css('text-align', 'right');\n }\n }\n\n // Show/Hide access key\n jQuery('#apbct_showApiKey').on('click', function(e) {\n e.preventDefault();\n jQuery(this).hide();\n jQuery('.apbct_settings-field--api_key').val(jQuery('.apbct_settings-field--api_key').attr('key'));\n jQuery('.apbct_settings-field--api_key+div').css('display', 'inline');\n });\n\n /**\n * Validate apikey and hide get auto btn\n */\n jQuery( document ).on('click', '#apbct_settings_templates_import_button', function() {\n jQuery('#apbct-ajax-result').remove();\n let optionSelected = jQuery('option:selected', jQuery('#apbct_settings_templates_import'));\n let templateNameInput = jQuery('#apbct_settings_templates_import_name');\n templateNameInput.css('border-color', 'inherit');\n if ( typeof optionSelected.data('id') === 'undefined' ) {\n console.log( 'Attribute \"data-id\" not set for the option.' );\n return;\n }\n let data = {\n 'template_id': optionSelected.data('id'),\n 'template_name': optionSelected.data('name'),\n 'settings': optionSelected.data('settings'),\n };\n let button = this;\n apbct_admin_sendAJAX(\n {action: 'settings_templates_import', data: data},\n {\n timeout: 25000,\n button: button,\n spinner: jQuery('#apbct_settings_templates_import_button .apbct_preloader_button' ),\n notJson: true,\n callback: function(result, data, params, obj) {\n if (result.success) {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n jQuery('#apbct_settings_templates_import_button .apbct_success').show(300);\n setTimeout(function() {\n jQuery('#apbct_settings_templates_import_button .apbct_success').hide(300);\n }, 2000);\n document.addEventListener('cleantalkModalClosed', function( e ) {\n document.location.reload();\n });\n setTimeout(function() {\n cleantalkModal.close();\n }, 2000);\n } else {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n }\n },\n },\n );\n });\n\n // Export settings\n jQuery( document ).on('click', '#apbct_settings_templates_export_button', function() {\n jQuery('#apbct-ajax-result').remove();\n let optionSelected = jQuery('option:selected', jQuery('#apbct_settings_templates_export'));\n let templateNameInput = jQuery('#apbct_settings_templates_export_name');\n let data = {};\n templateNameInput.css('border-color', 'inherit');\n if ( typeof optionSelected.data('id') === 'undefined' ) {\n console.log( 'Attribute \"data-id\" not set for the option.' );\n return;\n }\n if ( optionSelected.data('id') === 'new_template' ) {\n let templateName = templateNameInput.val();\n if ( templateName === '' ) {\n templateNameInput.css('border-color', 'red');\n return;\n }\n data = {\n 'template_name': templateName,\n };\n } else {\n data = {\n 'template_id': optionSelected.data('id'),\n };\n }\n let button = this;\n apbct_admin_sendAJAX(\n {action: 'settings_templates_export', data: data},\n {\n timeout: 25000,\n button: button,\n spinner: jQuery('#apbct_settings_templates_export_button .apbct_preloader_button' ),\n notJson: true,\n callback: function(result, data, params, obj) {\n if (result.success) {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n jQuery('#apbct_settings_templates_export_button .apbct_success').show(300);\n setTimeout(function() {\n jQuery('#apbct_settings_templates_export_button .apbct_success').hide(300);\n }, 2000);\n document.addEventListener('cleantalkModalClosed', function( e ) {\n document.location.reload();\n });\n setTimeout(function() {\n cleantalkModal.close();\n }, 2000);\n } else {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n }\n },\n },\n );\n });\n\n // Reset settings\n jQuery( document ).on('click', '#apbct_settings_templates_reset_button', function() {\n let button = this;\n apbct_admin_sendAJAX(\n {action: 'settings_templates_reset'},\n {\n timeout: 25000,\n button: button,\n spinner: jQuery('#apbct_settings_templates_reset_button .apbct_preloader_button' ),\n notJson: true,\n callback: function(result, data, params, obj) {\n if (result.success) {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n jQuery('#apbct_settings_templates_reset_button .apbct_success').show(300);\n setTimeout(function() {\n jQuery('#apbct_settings_templates_reset_button .apbct_success').hide(300);\n }, 2000);\n document.addEventListener('cleantalkModalClosed', function( e ) {\n document.location.reload();\n });\n setTimeout(function() {\n cleantalkModal.close();\n }, 2000);\n } else {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n }\n },\n },\n );\n });\n\n // Sync button\n jQuery('#apbct_button__sync').on('click', function() {\n apbct_admin_sendAJAX(\n {action: 'apbct_sync'},\n {\n timeout: 25000,\n button: document.getElementById('apbct_button__sync' ),\n spinner: jQuery('#apbct_button__sync .apbct_preloader_button' ),\n callback: function(result, data, params, obj) {\n jQuery('#apbct_button__sync .apbct_success').show(300);\n setTimeout(function() {\n jQuery('#apbct_button__sync .apbct_success').hide(300);\n }, 2000);\n if (result.reload) {\n if ( ctSettingsPage.key_changed ) {\n jQuery('.key_changed_sync').hide(300);\n jQuery('.key_changed_success').show(300);\n setTimeout(function() {\n document.location.reload();\n }, 3000);\n } else {\n document.location.reload();\n }\n }\n },\n },\n );\n });\n\n if ( ctSettingsPage.key_changed ) {\n jQuery('#apbct_button__sync').click();\n }\n\n jQuery(document).on('click', '.apbct_settings-long_description---show', function() {\n self = jQuery(this);\n apbctSettingsShowDescription(self, self.attr('setting'));\n });\n\n if (jQuery('#cleantalk_notice_renew').length || jQuery('#cleantalk_notice_trial').length) {\n apbctBannerCheck();\n }\n\n jQuery(document).on('change', '#apbct_settings_templates_export', function() {\n let optionSelected = jQuery('option:selected', this);\n if ( optionSelected.data('id') === 'new_template' ) {\n jQuery(this).parent().parent().find('#apbct_settings_templates_export_name').show();\n } else {\n jQuery(this).parent().parent().find('#apbct_settings_templates_export_name').hide();\n }\n });\n\n apbctSaveButtonPosition();\n let debounceTimer;\n window.addEventListener('scroll', function() {\n clearTimeout(debounceTimer);\n debounceTimer = setTimeout(function() {\n apbctSaveButtonPosition();\n }, 50);\n apbctNavigationMenuPosition();\n });\n jQuery('#ct_adv_showhide a').on('click', apbctSaveButtonPosition);\n\n\n /**\n * Change cleantalk account email\n */\n jQuery('#apbct-change-account-email').on('click', function(e) {\n e.preventDefault();\n\n let $this = jQuery(this);\n let accountEmailField = jQuery('#apbct-account-email');\n let accountEmail = accountEmailField.text();\n\n $this.toggleClass('active');\n\n if ($this.hasClass('active')) {\n $this.text($this.data('save-text'));\n accountEmailField.attr('contenteditable', 'true');\n accountEmailField.on('keydown', function(e) {\n if (e.code === 'Enter') {\n e.preventDefault();\n }\n });\n accountEmailField.on('input', function(e) {\n if (e.inputType === 'insertParagraph') {\n e.preventDefault();\n }\n });\n } else {\n apbct_admin_sendAJAX(\n {\n action: 'apbct_update_account_email',\n accountEmail: accountEmail,\n },\n {\n timeout: 5000,\n callback: function(result, data, params, obj) {\n if (result.error !== undefined) {\n jQuery('#apbct-account-email').css('border-color', 'red');\n }\n },\n },\n );\n\n accountEmailField.attr('contenteditable', 'false');\n $this.text($this.data('default-text'));\n }\n });\n\n /**\n * Validate apkikey and hide get auto btn\n */\n jQuery('#apbct_setting_apikey').on('input', function() {\n let enteredValue = jQuery(this).val();\n jQuery('#apbct_settings__key_line__save_settings').off('click');\n let keyBad = enteredValue !== '' && enteredValue.match(/^[a-z\\d]{8,30}\\s*$/) === null;\n jQuery('#apbct_settings__key_is_bad').hide();\n jQuery('#apbct_showApiKey').hide();\n jQuery('#apbct_settings__account_name_ob').hide();\n if (enteredValue === '') {\n jQuery('#apbct_button__key_line__save_changes_wrapper').hide();\n if (jQuery('#apbct_button__get_key_auto').length) {\n jQuery('#apbct_button__get_key_auto__wrapper').show();\n }\n } else {\n jQuery('#apbct_button__key_line__save_changes_wrapper').show();\n jQuery('#apbct_button__get_key_auto__wrapper').hide();\n if (keyBad) {\n jQuery('#apbct_settings__key_line__save_settings').on('click',\n function(e) {\n e.preventDefault();\n jQuery('#apbct_settings__key_is_bad').show();\n apbctHighlightElement('apbct_setting_apikey', 3);\n },\n );\n }\n }\n });\n\n if ( jQuery('#apbct_setting_apikey').val() && ctSettingsPage.key_is_ok) {\n jQuery('#apbct_button__get_key_auto__wrapper').hide();\n }\n\n /**\n * Handle synchronization errors when key is no ok to force user check the key and restart the sync\n */\n if ( !ctSettingsPage.key_is_ok && !ctSettingsPage.ip_license ) {\n jQuery('button.cleantalk_link[value=\"save_changes\"]').on('click',\n function(e) {\n e.preventDefault();\n if (!jQuery('#sync_required_notice').length) {\n jQuery( '

' +\n 'Synchronization process failed. Please, check the acces key and restart the synch.' +\n '

' ).insertAfter( jQuery('#apbct_button__sync') );\n }\n apbctHighlightElement('apbct_setting_apikey', 3);\n apbctHighlightElement('apbct_button__sync', 3);\n jQuery('#apbct_button__get_key_auto__wrapper').show();\n },\n );\n }\n\n /**\n * Open WP gallery for adding custom logo\n */\n jQuery('#apbct-custom-logo-open-gallery').click(function(e) {\n e.preventDefault();\n\n const button = jQuery(this);\n\n const customUploader = wp.media({\n library: {\n type: 'image',\n },\n multiple: false,\n });\n\n customUploader.on('select', function() {\n const image = customUploader.state().get('selection').first().toJSON();\n\n button.parent().prev().attr( 'src', image.url );\n jQuery('#cleantalk_custom_logo').val( image.id );\n });\n\n customUploader.open();\n });\n\n /**\n * Remove selected logo\n */\n jQuery('#apbct-custom-logo-remove-image').click(function(e) {\n e.preventDefault();\n\n if ( true === confirm( 'Sure?' ) ) {\n const src = jQuery(this).parent().prev().data('src');\n jQuery(this).parent().prev().attr('src', src);\n jQuery(this).prev().prev().val('');\n }\n });\n\n jQuery('button[id*=\"apbct-action-adjust-change-\"]').click(function(e) {\n e.preventDefault();\n\n let data = {};\n data.action = 'apbct_action_adjust_change';\n data.adjust = jQuery(this).data('adjust');\n\n let params = {};\n params.button = document.getElementById('apbct-action-adjust-change-' + data.adjust);\n params.notJson = true;\n\n params.callback = function() {\n document.location.reload();\n };\n\n apbct_admin_sendAJAX(data, params);\n });\n\n jQuery('button[id*=\"apbct-action-adjust-reverse-\"]').click(function(e) {\n e.preventDefault();\n\n let data = {};\n data.action = 'apbct_action_adjust_reverse';\n data.adjust = jQuery(this).data('adjust');\n\n let params = {};\n params.button = document.getElementById('apbct-action-adjust-reverse-' + data.adjust);\n params.notJson = true;\n\n params.callback = function() {\n document.location.reload();\n };\n\n apbct_admin_sendAJAX(data, params);\n });\n\n document.querySelector('.apbct_hidden_section_nav_mob_btn')?.addEventListener('click', () => {\n document.querySelector('#apbct_hidden_section_nav ul').style.display = 'block';\n document.querySelector('.apbct_hidden_section_nav_mob_btn').style.display = 'none';\n });\n\n document.querySelector('.apbct_hidden_section_nav_mob_btn-close')?.addEventListener('click', () => {\n document.querySelector('#apbct_hidden_section_nav ul').style.display = 'none';\n document.querySelector('.apbct_hidden_section_nav_mob_btn').style.display = 'block';\n });\n\n // Hide/show EmailEncoder replacing text textarea\n apbctManageEmailEncoderCustomTextField();\n\n // Turn SpamFireWall on with Anti-Crawler\n apbctManageAntiCrawlerDependency();\n\n if (window.location.hash) {\n const anchor = window.location.hash.substring(1);\n handleAnchorDetection(anchor);\n }\n\n // Fullpage trial/renew banner dismiss handler\n jQuery('body').on('click', '.apbct-trial-renew-fullpage .notice-dismiss', function(e) {\n e.preventDefault();\n sessionStorage.setItem('apbct_trial_fullpage_dismissed', '1');\n jQuery('.apbct-trial-renew-fullpage').hide();\n jQuery('#apbct-settings-page-wrap').show();\n });\n});\n\n/**\n * Detect ancors and open advanced settings before scroll\n * @param {string} anchor\n */\nfunction handleAnchorDetection(anchor) {\n let advSettings = document.querySelector('#apbct_settings__advanced_settings');\n if ( 'none' === advSettings.style.display ) {\n apbctExceptedShowHide('apbct_settings__advanced_settings');\n }\n scrollToAnchor('#' + anchor);\n}\n\n/**\n * Scroll to the target element ID\n * @param {string} anchorId Anchor target element ID\n */\nfunction scrollToAnchor(anchorId) {\n const targetElement = document.querySelector(anchorId);\n if (targetElement) {\n targetElement.scrollIntoView({\n block: 'end',\n });\n }\n}\n\n/**\n * Hide/show EmailEncoder replacing text textarea\n */\nfunction apbctManageEmailEncoderCustomTextField() {\n const replacingText = document\n .querySelector('#apbct_setting_data__email_decoder_obfuscation_custom_text');\n let replacingTextWrapperSub;\n if (replacingText !== null) {\n replacingTextWrapperSub = typeof replacingText.parentElement !== 'undefined' ?\n replacingText.parentElement :\n null;\n }\n document.querySelectorAll('.apbct_setting---data__email_decoder_obfuscation_mode').forEach((elem) => {\n // visibility set on saved settings\n if (replacingTextWrapperSub && elem.checked && elem.value !== 'replace') {\n replacingTextWrapperSub.classList.add('hidden');\n }\n // visibility set on change\n elem.addEventListener('click', (event) => {\n if (typeof replacingTextWrapperSub !== 'undefined') {\n if (event.target.value === 'replace') {\n replacingTextWrapperSub.classList.remove('hidden');\n } else {\n replacingTextWrapperSub.classList.add('hidden');\n }\n }\n });\n });\n}\n\n/**\n * Anti-Crawler is an add-on to SFW, so check SpamFireWall on enabling Anti-Crawler\n */\nfunction apbctManageAntiCrawlerDependency() {\n const antiCrawler = document.querySelector('#apbct_setting_sfw__anti_crawler');\n const spamFireWall = document.querySelector('#apbct_setting_sfw__enabled');\n if (!antiCrawler || !spamFireWall) {\n return;\n }\n antiCrawler.addEventListener('change', () => {\n if (! antiCrawler.checked || spamFireWall.checked) {\n return;\n }\n spamFireWall.checked = true;\n const childrens = spamFireWall.getAttribute('apbct_children');\n if (childrens !== null) {\n apbctSettingsDependencies(childrens, 1);\n }\n });\n}\n\n/**\n * Checking current account status for renew notice\n */\nfunction apbctBannerCheck() {\n let bannerChecker = setInterval( function() {\n apbct_admin_sendAJAX(\n {action: 'apbct_settings__check_renew_banner'},\n {\n callback: function(result, data, params, obj) {\n if (result.close_renew_banner) {\n if (jQuery('#cleantalk_notice_renew').length) {\n jQuery('#cleantalk_notice_renew').hide('slow');\n }\n if (jQuery('#cleantalk_notice_trial').length) {\n jQuery('#cleantalk_notice_trial').hide('slow');\n }\n clearInterval(bannerChecker);\n }\n },\n },\n );\n }, 900000);\n}\n\n/**\n * Select elems like #{selector} or .{selector}\n * Selector passed in string separated by ,\n *\n * @param {string|array} elems\n * @return {*}\n */\nfunction apbctGetElems(elems) {\n elems = elems.split(',');\n for ( let i=0, len = elems.length, tmp; i < len; i++) {\n tmp = jQuery('#'+elems[i]);\n elems[i] = tmp.length === 0 ? jQuery('.'+elems[i]) : tmp;\n }\n return elems;\n}\n\n/**\n * Select elems like #{selector} or .{selector}\n * Selector could be passed in a string ( separated by comma ) or in array ( [ elem1, elem2, ... ] )\n *\n * @param {string|array} elems\n * @return {array}\n */\nfunction apbctGetElemsNative(elems) {\n // Make array from a string\n if (typeof elems === 'string') {\n elems = elems.split(',');\n }\n\n let out = [];\n\n elems.forEach(function(elem, i, arr) {\n // try to get elements with such IDs\n let tmp = document.getElementById(elem);\n if (tmp !== null) {\n out.push( tmp[key] );\n return;\n }\n\n // try to get elements with such class name\n // write each elem from collection to new element of output array\n tmp = document.getElementsByClassName(elem);\n if (tmp !== null && tmp.length !==0 ) {\n for (key in tmp) {\n if ( +key >= 0 ) {\n out.push( tmp[key] );\n }\n }\n }\n });\n\n return out;\n}\n\n/**\n * @param {string|array} elems\n */\nfunction apbctShowHideElem(elems) {\n elems = apbctGetElems(elems);\n for ( let i=0, len = elems.length; i < len; i++) {\n elems[i].each(function(i, elem) {\n elem = jQuery(elem);\n let label = elem.next('label') || elem.prev('label') || null;\n if (elem.is(':visible')) {\n elem.hide();\n if (label) label.hide();\n } else {\n elem.show();\n if (label) label.show();\n }\n });\n }\n}\n\n/**\n * @param {string|array} element\n */\nfunction apbctExceptedShowHide(element) { // eslint-disable-line no-unused-vars\n let toHide = [\n 'apbct_settings__dwpms_settings',\n 'apbct_settings__advanced_settings',\n 'trusted_and_affiliate__special_span',\n ];\n let index = toHide.indexOf(element);\n if (index !== -1) {\n toHide.splice(index, 1);\n }\n apbctShowHideElem(element);\n toHide.forEach((toHideElem) => {\n if (document.getElementById(toHideElem) && document.getElementById(toHideElem).style.display !== 'none') {\n apbctShowHideElem(toHideElem);\n }\n });\n}\n\n/**\n * @param {mixed} event\n * @param {string} id\n */\nfunction apbctShowRequiredGroups(event, id) { // eslint-disable-line no-unused-vars\n let required = document.getElementById('apbct_settings__dwpms_settings');\n if (required && required.style.display === 'none') {\n let originEvent = event;\n event.preventDefault();\n apbctShowHideElem('apbct_settings__dwpms_settings');\n document.getElementById(id).dispatchEvent(new originEvent.constructor(originEvent.type, originEvent));\n }\n}\n\n/**\n * Settings dependences. Switch|toggle depended elements state (disabled|enabled)\n * Recieve list of selectors ( without class mark (.) or id mark (#) )\n *\n * @param {string|array} ids\n * @param {int} enable\n */\nfunction apbctSettingsDependencies(ids, enable) { // eslint-disable-line no-unused-vars\n enable = ! isNaN(enable) ? enable : null;\n\n // Get elements\n let elems = apbctGetElemsNative( ids );\n\n elems.forEach(function(elem, i, arr) {\n let doDisable = function() {\n elem.setAttribute('disabled', 'disabled');\n };\n let doEnable = function() {\n elem.removeAttribute('disabled');\n };\n\n // Set defined state\n if (enable === null) {\n enable = elem.getAttribute('disabled') === null ? 0 : 1;\n }\n\n enable === 1 ? doEnable() : doDisable();\n\n if ( elem.getAttribute('apbct_children') !== null) {\n let state = apbctSettingsDependenciesGetState( elem ) && enable;\n if ( state !== null ) {\n apbctSettingsDependencies( elem.getAttribute('apbct_children'), state );\n }\n }\n });\n}\n\n/**\n * @param {HTMLElement} elem\n * @return {int|null}\n */\nfunction apbctSettingsDependenciesGetState(elem) { // eslint-disable-line no-unused-vars\n let state;\n\n switch ( elem.getAttribute( 'type' ) ) {\n case 'checkbox':\n state = +elem.checked;\n break;\n case 'radio':\n state = +(+elem.getAttribute('value') === 1);\n break;\n default:\n state = null;\n }\n\n return state;\n}\n\n/**\n * Warn user about cookie type change if cache solutions found in environment.\n * #Call inlined from SettingsField\n * @param {object} event\n */\nfunction onApbctCookieTypeChange(event) { // eslint-disable-line no-unused-vars\n const switchToMode = event?.target?.value?.toString() || null;\n if (\n switchToMode !== null &&\n (\n switchToMode === '1' || // cookies on\n switchToMode === '0' // cookies off\n )\n ) {\n cleantalkModal.loaded = false;\n cleantalkModal.open(false);\n cleantalkModal.confirm(\n __('Attention!', 'cleantalk-spam-protect'),\n (\n __(\n 'Cache solutions detected. ',\n 'cleantalk-spam-protect',\n ) +\n __(\n 'Switching cookie mode to \\'On\\' or \\'Off\\' may affect filtering quality. ',\n 'cleantalk-spam-protect',\n ) +\n __('The recommended setting is \\'Auto\\'.', 'cleantalk-spam-protect')\n ),\n '',\n (decision)=>{\n decision === true && jQuery('#apbct_setting_data__set_cookies__Auto').click();\n },\n __('Set to \"Auto\"', 'cleantalk-spam-protect'),\n __('Confirm mode change', 'cleantalk-spam-protect'),\n );\n }\n}\n\n/**\n * @param {HTMLElement} label\n * @param {string} settingId\n */\nfunction apbctSettingsShowDescription(label, settingId) {\n let removeDescFunc = function(e) {\n const callerIsPopup = jQuery(e.target).parent('.apbct_long_desc').length != 0;\n const callerIsHideCross = jQuery(e.target).hasClass('apbct_long_desc__cancel');\n const descIsShown = jQuery('.apbct_long_desc__title').length > 0;\n if (descIsShown && !callerIsPopup || callerIsHideCross) {\n jQuery('.apbct_long_desc').remove();\n jQuery(document).off('click', removeDescFunc);\n }\n };\n\n label.after('
');\n let obj = jQuery('#apbct_long_desc__'+settingId);\n obj.append('')\n .append('
')\n .css({\n top: label.position().top - 5,\n left: label.position().left + 25,\n });\n\n\n apbct_admin_sendAJAX(\n {action: 'apbct_settings__get__long_description', setting_id: settingId},\n {\n spinner: obj.children('img'),\n callback: function(result, data, params, obj) {\n if (result && result.title && result.desc) {\n obj.empty()\n .append('
')\n .append('')\n .append('

'+result.title+'

')\n .append('

'+result.desc+'

');\n\n jQuery(document).on('click', removeDescFunc);\n }\n },\n },\n obj,\n );\n}\n\n/**\n * Set position for navigation menu\n * @return {void}\n */\nfunction apbctNavigationMenuPosition() {\n const navBlock = document.querySelector('#apbct_hidden_section_nav ul');\n const rightBtnSave = document.querySelector('#apbct_settings__button_section');\n if (!navBlock || !rightBtnSave) {\n return;\n }\n const scrollPosition = window.scrollY;\n const windowWidth = window.innerWidth;\n if (scrollPosition > 1000) {\n navBlock.style.position = 'fixed';\n rightBtnSave.style.position = 'fixed';\n } else {\n navBlock.style.position = 'static';\n rightBtnSave.style.position = 'static';\n }\n\n if (windowWidth < 768) {\n rightBtnSave.style.position = 'fixed';\n }\n}\n\n/**\n * Set position for save button, hide it if scrolled to the bottom\n * @return {void}\n */\nfunction apbctSaveButtonPosition() {\n if (\n document.getElementById('apbct_settings__before_advanced_settings') === null ||\n document.getElementById('apbct_settings__after_advanced_settings') === null ||\n document.getElementById('apbct_settings__button_section') === null ||\n document.getElementById('apbct_settings__advanced_settings') === null ||\n document.getElementById('apbct_hidden_section_nav') === null\n ) {\n return;\n }\n\n if (!ctSettingsPage.key_is_ok && !ctSettingsPage.ip_license) {\n jQuery('#apbct_settings__main_save_button').hide();\n return;\n }\n\n const additionalSaveButton =\n document.querySelector('#apbct_settings__button_section, cleantalk_link[value=\"save_changes\"]');\n if (!additionalSaveButton) {\n return;\n }\n\n const scrollPosition = window.scrollY;\n const documentHeight = document.documentElement.scrollHeight;\n const windowHeight = window.innerHeight;\n const threshold = 800;\n if (scrollPosition + windowHeight >= documentHeight - threshold) {\n additionalSaveButton.style.display = 'none';\n } else {\n additionalSaveButton.style.display = 'block';\n }\n\n const advSettingsBlock = document.getElementById('apbct_settings__advanced_settings');\n const mainSaveButton = document.getElementById('apbct_settings__block_main_save_button');\n if (!advSettingsBlock || !mainSaveButton) {\n return;\n }\n\n if (advSettingsBlock.style.display == 'none') {\n mainSaveButton.classList.remove('apbct_settings__position_main_save_button');\n } else {\n mainSaveButton.classList.add('apbct_settings__position_main_save_button');\n }\n}\n\n/**\n * Hightlights element\n *\n * @param {string} id\n * @param {int} times\n */\nfunction apbctHighlightElement(id, times) {\n times = times-1 || 0;\n let keyField = jQuery('#'+id);\n jQuery('html, body').animate({scrollTop: keyField.offset().top - 100}, 'slow');\n keyField.addClass('apbct_highlighted');\n keyField.animate({opacity: 0}, 400, 'linear', function() {\n keyField.animate({opacity: 1}, 400, 'linear', function() {\n if (times>0) {\n apbctHighlightElement(id, times);\n } else {\n keyField.removeClass('apbct_highlighted');\n }\n });\n });\n}\n\n/**\n * Open modal to create support user\n */\nfunction apbctCreateSupportUser() { // eslint-disable-line no-unused-vars\n const localTextArray = ctSettingsPage.support_user_creation_msg_array;\n cleantalkModal.loaded = false;\n cleantalkModal.open(false);\n cleantalkModal.confirm(\n localTextArray.confirm_header,\n localTextArray.confirm_text,\n '',\n apbctCreateSupportUserCallback,\n );\n}\n\n/**\n * Create support user\n */\nfunction apbctCreateSupportUserCallback() {\n const preloader = jQuery('#apbct_summary_and_support-create_user_button_preloader');\n preloader.css('display', 'block');\n apbct_admin_sendAJAX(\n {\n action: 'apbct_action__create_support_user',\n },\n {\n timeout: 10000,\n notJson: 1,\n callback: function(result, data, params, obj) {\n let localTextArray = ctSettingsPage.support_user_creation_msg_array;\n let popupMsg = localTextArray.default_error;\n const responseValid = (\n typeof result === 'object' &&\n result.hasOwnProperty('success') &&\n result.hasOwnProperty('user_created') &&\n result.hasOwnProperty('mail_sent') &&\n result.hasOwnProperty('cron_updated') &&\n result.hasOwnProperty('user_data') &&\n result.hasOwnProperty('result_code') &&\n typeof result.user_data === 'object' &&\n result.user_data.hasOwnProperty('username') &&\n result.user_data.hasOwnProperty('email') &&\n result.user_data.hasOwnProperty('password')\n );\n if (responseValid && result.success) {\n if (result.user_created) {\n let mailSentMsg = '';\n let successCreationMsg = '';\n let cronUpdatedMsg = localTextArray.cron_updated;\n\n if (result.mail_sent) {\n mailSentMsg = localTextArray.mail_sent_success;\n } else {\n mailSentMsg = localTextArray.mail_sent_error;\n }\n\n if (result.result_code === 0) {\n successCreationMsg = localTextArray.user_updated;\n } else {\n successCreationMsg = localTextArray.user_created;\n }\n\n jQuery('#apbct_summary_and_support-user_creation_username').text(result.user_data.username);\n jQuery('#apbct_summary_and_support-user_creation_email').text(result.user_data.email);\n jQuery('#apbct_summary_and_support-user_creation_password').text(result.user_data.password);\n jQuery('#apbct_summary_and_support-user_creation_mail_sent').text(mailSentMsg);\n jQuery('#apbct_summary_and_support-user_creation_title').text(successCreationMsg);\n jQuery('#apbct_summary_and_support-user_creation_cron_updated').text(cronUpdatedMsg);\n jQuery('.apbct_summary_and_support-user_creation_result').css('display', 'block');\n const createUserButton = jQuery('#apbct_summary_and_support-create_user_button');\n createUserButton.attr('disabled', true);\n createUserButton.css('color', 'rgba(93,89,86,0.55)');\n createUserButton.css('background', '#cccccc');\n preloader.css('display', 'none');\n return;\n } else {\n if (result.result_code === -2) {\n popupMsg = localTextArray.invalid_permission;\n } else if (result.result_code === -1) {\n popupMsg = localTextArray.unknown_creation_error;\n } else if (result.result_code === -4) {\n popupMsg = localTextArray.on_cooldown;\n } else if (result.result_code === -5) {\n popupMsg = localTextArray.email_is_busy;\n }\n }\n }\n preloader.css('display', 'none');\n cleantalkModal.loaded = popupMsg;\n cleantalkModal.open();\n },\n errorOutput: function(msg) {\n preloader.css('display', 'none');\n cleantalkModal.loaded = msg;\n cleantalkModal.open();\n },\n },\n );\n}\n"],"names":["__","wp","i18n","handleAnchorDetection","anchor","document","querySelector","style","display","apbctExceptedShowHide","scrollToAnchor","anchorId","targetElement","scrollIntoView","block","apbctManageEmailEncoderCustomTextField","replacingText","let","replacingTextWrapperSub","parentElement","querySelectorAll","forEach","elem","checked","value","classList","add","addEventListener","event","target","remove","apbctManageAntiCrawlerDependency","antiCrawler","spamFireWall","childrens","getAttribute","apbctSettingsDependencies","apbctBannerCheck","bannerChecker","setInterval","apbct_admin_sendAJAX","action","callback","result","data","params","obj","close_renew_banner","jQuery","length","hide","clearInterval","apbctGetElems","elems","i","len","split","tmp","apbctGetElemsNative","out","arr","getElementById","push","key","getElementsByClassName","apbctShowHideElem","each","label","next","prev","is","show","element","toHide","index","indexOf","splice","toHideElem","apbctShowRequiredGroups","id","required","originEvent","preventDefault","dispatchEvent","constructor","type","ids","enable","isNaN","state","removeAttribute","setAttribute","apbctSettingsDependenciesGetState","onApbctCookieTypeChange","switchToMode","toString","cleantalkModal","loaded","open","confirm","decision","click","apbctSettingsShowDescription","settingId","removeDescFunc","e","callerIsPopup","parent","callerIsHideCross","hasClass","off","after","append","css","top","position","left","setting_id","spinner","children","title","desc","empty","on","apbctNavigationMenuPosition","scrollPosition","windowWidth","navBlock","rightBtnSave","window","scrollY","innerWidth","apbctSaveButtonPosition","advSettingsBlock","mainSaveButton","ctSettingsPage","key_is_ok","ip_license","additionalSaveButton","documentHeight","documentElement","scrollHeight","innerHeight","apbctHighlightElement","times","keyField","animate","scrollTop","offset","addClass","opacity","removeClass","apbctCreateSupportUser","localTextArray","support_user_creation_msg_array","confirm_header","confirm_text","apbctCreateSupportUserCallback","preloader","timeout","notJson","popupMsg","default_error","hasOwnProperty","user_data","success","user_created","mailSentMsg","successCreationMsg","cronUpdatedMsg","cron_updated","createUserButton","mail_sent","mail_sent_success","mail_sent_error","result_code","user_updated","text","username","email","password","attr","invalid_permission","unknown_creation_error","on_cooldown","email_is_busy","errorOutput","msg","ready","getComputedStyle","direction","this","val","optionSelected","console","log","template_id","template_name","settings","button","insertAfter","setTimeout","location","reload","close","templateNameInput","templateName","key_changed","self","find","debounceTimer","clearTimeout","$this","accountEmailField","accountEmail","toggleClass","code","inputType","undefined","error","enteredValue","keyBad","match","customUploader","media","library","multiple","image","get","first","toJSON","url","src","adjust","hash","substring","sessionStorage","setItem"],"mappings":"AAAA,IAAOA,GAAMC,GAAGC,KAAP,GAwaT,SAASC,sBAAsBC,GAEtB,SADaC,SAASC,cAAc,oCAAoC,EACjDC,MAAMC,SAC9BC,sBAAsB,mCAAmC,EAE7DC,eAAe,IAAMN,CAAM,CAC/B,CAMA,SAASM,eAAeC,GACdC,EAAgBP,SAASC,cAAcK,CAAQ,EACjDC,GACAA,EAAcC,eAAe,CACzBC,MAAO,KACX,CAAC,CAET,CAKA,SAASC,yCACL,IAAMC,EAAgBX,SACjBC,cAAc,4DAA4D,EAC/EW,IAAIC,EACkB,OAAlBF,IACAE,EAAiE,KAAA,IAAhCF,EAAcG,cAC3CH,EAAcG,cACd,MAERd,SAASe,iBAAiB,uDAAuD,EAAEC,QAAQ,IAEnFH,GAA2BI,EAAKC,SAA0B,YAAfD,EAAKE,OAChDN,EAAwBO,UAAUC,IAAI,QAAQ,EAGlDJ,EAAKK,iBAAiB,QAAS,IACY,KAAA,IAA5BT,IACoB,YAAvBU,EAAMC,OAAOL,MACbN,EAAwBO,UAAUK,OAAO,QAAQ,EAEjDZ,EAAwBO,UAAUC,IAAI,QAAQ,EAG1D,CAAC,CACL,CAAC,CACL,CAKA,SAASK,mCACL,IAAMC,EAAc3B,SAASC,cAAc,kCAAkC,EACvE2B,EAAe5B,SAASC,cAAc,6BAA6B,EACpE0B,GAAgBC,GAGrBD,EAAYL,iBAAiB,SAAU,KACnC,IAIMO,EAJAF,EAAYT,SAAWU,CAAAA,EAAaV,UAG1CU,EAAaV,QAAU,CAAA,EAEL,QADZW,EAAYD,EAAaE,aAAa,gBAAgB,KAExDC,0BAA0BF,EAAW,CAAC,CAE9C,CAAC,CACL,CAKA,SAASG,mBACLpB,IAAIqB,EAAgBC,YAAa,WAC7BC,qBACI,CAACC,OAAQ,oCAAoC,EAC7C,CACIC,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACjCH,EAAOI,qBACHC,OAAO,yBAAyB,EAAEC,QAClCD,OAAO,yBAAyB,EAAEE,KAAK,MAAM,EAE7CF,OAAO,yBAAyB,EAAEC,QAClCD,OAAO,yBAAyB,EAAEE,KAAK,MAAM,EAEjDC,cAAcb,CAAa,EAEnC,CACJ,CACJ,CACJ,EAAG,GAAM,CACb,CASA,SAASc,cAAcC,GAEnB,IAAMpC,IAAIqC,EAAE,EAAGC,GADfF,EAAQA,EAAMG,MAAM,GAAG,GACIP,OAAQQ,EAAKH,EAAIC,EAAKD,CAAC,GAC9CG,EAAMT,OAAO,IAAIK,EAAMC,EAAE,EACzBD,EAAMC,GAAoB,IAAfG,EAAIR,OAAeD,OAAO,IAAIK,EAAMC,EAAE,EAAIG,EAEzD,OAAOJ,CACX,CASA,SAASK,oBAAoBL,GAEJ,UAAjB,OAAOA,IACPA,EAAQA,EAAMG,MAAM,GAAG,GAG3BvC,IAAI0C,EAAM,GAsBV,OApBAN,EAAMhC,QAAQ,SAASC,EAAMgC,EAAGM,GAE5B3C,IAAIwC,EAAMpD,SAASwD,eAAevC,CAAI,EACtC,GAAY,OAARmC,EACAE,EAAIG,KAAML,EAAIM,IAAK,OAOvB,GAAY,QADZN,EAAMpD,SAAS2D,uBAAuB1C,CAAI,IACR,IAAdmC,EAAIR,OACpB,IAAKc,OAAON,EACK,GAAR,CAACM,KACFJ,EAAIG,KAAML,EAAIM,IAAK,CAInC,CAAC,EAEMJ,CACX,CAKA,SAASM,kBAAkBZ,GAEvB,IAAMpC,IAAIqC,EAAE,EAAGC,GADfF,EAAQD,cAAcC,CAAK,GACAJ,OAAQK,EAAIC,EAAKD,CAAC,GACzCD,EAAMC,GAAGY,KAAK,SAASZ,EAAGhC,GAEtBL,IAAIkD,GADJ7C,EAAO0B,OAAO1B,CAAI,GACD8C,KAAK,OAAO,GAAK9C,EAAK+C,KAAK,OAAO,GAAK,KACpD/C,EAAKgD,GAAG,UAAU,GAClBhD,EAAK4B,KAAK,EACNiB,GAAOA,EAAMjB,KAAK,IAEtB5B,EAAKiD,KAAK,EACNJ,GAAOA,EAAMI,KAAK,EAE9B,CAAC,CAET,CAKA,SAAS9D,sBAAsB+D,GAC3BvD,IAAIwD,EAAS,CACT,iCACA,oCACA,uCAEAC,EAAQD,EAAOE,QAAQH,CAAO,EACpB,CAAC,IAAXE,GACAD,EAAOG,OAAOF,EAAO,CAAC,EAE1BT,kBAAkBO,CAAO,EACzBC,EAAOpD,QAAQ,IACPhB,SAASwD,eAAegB,CAAU,GAA2D,SAAtDxE,SAASwD,eAAegB,CAAU,EAAEtE,MAAMC,SACjFyD,kBAAkBY,CAAU,CAEpC,CAAC,CACL,CAMA,SAASC,wBAAwBlD,EAAOmD,GACpC9D,IAAI+D,EAAW3E,SAASwD,eAAe,gCAAgC,EACnEmB,GAAuC,SAA3BA,EAASzE,MAAMC,WACvByE,EAAcrD,GACZsD,eAAe,EACrBjB,kBAAkB,gCAAgC,EAClD5D,SAASwD,eAAekB,CAAE,EAAEI,cAAc,IAAIF,EAAYG,YAAYH,EAAYI,KAAMJ,CAAW,CAAC,EAE5G,CASA,SAAS7C,0BAA0BkD,EAAKC,GACpCA,EAAWC,MAAMD,CAAM,EAAa,KAATA,EAGf7B,oBAAqB4B,CAAI,EAE/BjE,QAAQ,SAASC,EAAMgC,EAAGM,GAC5B3C,IAeQwE,EAHG,KAHPF,EADW,OAAXA,EAC2C,OAAlCjE,EAAKa,aAAa,UAAU,EAAa,EAAI,EAG1DoD,GARIjE,EAAKoE,gBAAgB,UAAU,EAH/BpE,EAAKqE,aAAa,WAAY,UAAU,EAaC,OAAxCrE,EAAKa,aAAa,gBAAgB,GAEpB,QADXsD,EAAQG,kCAAmCtE,CAAK,GAAKiE,IAErDnD,0BAA2Bd,EAAKa,aAAa,gBAAgB,EAAGsD,CAAM,CAGlF,CAAC,CACL,CAMA,SAASG,kCAAkCtE,GACvCL,IAAIwE,EAEJ,OAASnE,EAAKa,aAAc,MAAO,GACnC,IAAK,WACDsD,EAAQ,CAACnE,EAAKC,QACd,MACJ,IAAK,QACDkE,EAAQ,EAAkC,GAAhC,CAACnE,EAAKa,aAAa,OAAO,GACpC,MACJ,QACIsD,EAAQ,IACZ,CAEA,OAAOA,CACX,CAOA,SAASI,wBAAwBjE,GACvBkE,EAAelE,GAAOC,QAAQL,OAAOuE,SAAS,GAAK,KAEpC,OAAjBD,GAEqB,MAAjBA,GACiB,MAAjBA,IAGJE,eAAeC,OAAS,CAAA,EACxBD,eAAeE,KAAK,CAAA,CAAK,EACzBF,eAAeG,QACXnG,GAAG,aAAc,wBAAwB,EAErCA,GACI,6BACA,wBACJ,EACAA,GACI,wEACA,wBACJ,EACAA,GAAG,qCAAwC,wBAAwB,EAEvE,GACA,IACiB,CAAA,IAAboG,GAAqBpD,OAAO,wCAAwC,EAAEqD,MAAM,CAChF,EACArG,GAAG,gBAAiB,wBAAwB,EAC5CA,GAAG,sBAAuB,wBAAwB,CACtD,EAER,CAMA,SAASsG,6BAA6BnC,EAAOoC,GACpB,SAAjBC,EAA0BC,GAC1B,IAAMC,EAAsE,GAAtD1D,OAAOyD,EAAE5E,MAAM,EAAE8E,OAAO,kBAAkB,EAAE1D,OAC5D2D,EAAoB5D,OAAOyD,EAAE5E,MAAM,EAAEgF,SAAS,yBAAyB,GACd,EAA3C7D,OAAO,yBAAyB,EAAEC,QACnC,CAACyD,GAAiBE,KACjC5D,OAAO,kBAAkB,EAAElB,OAAO,EAClCkB,OAAO3C,QAAQ,EAAEyG,IAAI,QAASN,CAAc,EAEpD,CAEArC,EAAM4C,MAAM,6BAA8BR,EAAU,kCAAqC,EACzFtF,IAAI6B,EAAME,OAAO,qBAAqBuD,CAAS,EAC/CzD,EAAIkE,OAAO,gDAAkD,EACxDA,OAAO,4CAA8C,EACrDC,IAAI,CACDC,IAAK/C,EAAMgD,SAAS,EAAED,IAAM,EAC5BE,KAAMjD,EAAMgD,SAAS,EAAEC,KAAO,EAClC,CAAC,EAGL5E,qBACI,CAACC,OAAQ,wCAAyC4E,WAAYd,CAAS,EACvE,CACIe,QAASxE,EAAIyE,SAAS,KAAK,EAC3B7E,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACjCH,GAAUA,EAAO6E,OAAS7E,EAAO8E,OACjC3E,EAAI4E,MAAM,EACLV,OAAO,4CAA8C,EACrDA,OAAO,2DAA6D,EACpEA,OAAO,sCAAwCrE,EAAO6E,MAAM,OAAO,EACnER,OAAO,MAAMrE,EAAO8E,KAAK,MAAM,EAEpCzE,OAAO3C,QAAQ,EAAEsH,GAAG,QAASnB,CAAc,EAEnD,CACJ,EACA1D,CACJ,CACJ,CAMA,SAAS8E,8BACL,IAKMC,EACAC,EANAC,EAAW1H,SAASC,cAAc,8BAA8B,EAChE0H,EAAe3H,SAASC,cAAc,iCAAiC,EACxEyH,GAAaC,IAGZH,EAAiBI,OAAOC,QACxBJ,EAAcG,OAAOE,WACN,IAAjBN,GACAE,EAASxH,MAAM4G,SAAW,QAC1Ba,EAAazH,MAAM4G,SAAW,UAE9BY,EAASxH,MAAM4G,SAAW,SAC1Ba,EAAazH,MAAM4G,SAAW,UAG9BW,EAAc,OACdE,EAAazH,MAAM4G,SAAW,QAEtC,CAMA,SAASiB,0BACL,IAqBMP,EAUAQ,EACAC,EA/BsE,OAAxEjI,SAASwD,eAAe,0CAA0C,GACK,OAAvExD,SAASwD,eAAe,yCAAyC,GACH,OAA9DxD,SAASwD,eAAe,gCAAgC,GACS,OAAjExD,SAASwD,eAAe,mCAAmC,GACH,OAAxDxD,SAASwD,eAAe,0BAA0B,IAKjD0E,eAAeC,WAAcD,eAAeE,YAK3CC,EACFrI,SAASC,cAAc,uEAAuE,KAK5FuH,EAAiBI,OAAOC,QACxBS,EAAiBtI,SAASuI,gBAAgBC,aAI5CH,EAAqBnI,MAAMC,QADMmI,EADnB,KACdd,EAFiBI,OAAOa,YAGa,OAEA,QAGnCT,EAAmBhI,SAASwD,eAAe,mCAAmC,EAC9EyE,EAAiBjI,SAASwD,eAAe,wCAAwC,EAClFwE,IAAqBC,IAIY,QAAlCD,EAAiB9H,MAAMC,QACvB8H,EAAe7G,UAAUK,OAAO,2CAA2C,EAE3EwG,EAAe7G,UAAUC,IAAI,2CAA2C,GA7BxEsB,OAAO,mCAAmC,EAAEE,KAAK,EA+BzD,CAQA,SAAS6F,sBAAsBhE,EAAIiE,GAC/BA,EAAQA,EAAM,GAAK,EACnB/H,IAAIgI,EAAWjG,OAAO,IAAI+B,CAAE,EAC5B/B,OAAO,YAAY,EAAEkG,QAAQ,CAACC,UAAWF,EAASG,OAAO,EAAElC,IAAM,GAAG,EAAG,MAAM,EAC7E+B,EAASI,SAAS,mBAAmB,EACrCJ,EAASC,QAAQ,CAACI,QAAS,CAAC,EAAG,IAAK,SAAU,WAC1CL,EAASC,QAAQ,CAACI,QAAS,CAAC,EAAG,IAAK,SAAU,WAChC,EAANN,EACAD,sBAAsBhE,EAAIiE,CAAK,EAE/BC,EAASM,YAAY,mBAAmB,CAEhD,CAAC,CACL,CAAC,CACL,CAKA,SAASC,yBACL,IAAMC,EAAiBlB,eAAemB,gCACtC1D,eAAeC,OAAS,CAAA,EACxBD,eAAeE,KAAK,CAAA,CAAK,EACzBF,eAAeG,QACXsD,EAAeE,eACfF,EAAeG,aACf,GACAC,8BACJ,CACJ,CAKA,SAASA,iCACL,IAAMC,EAAY9G,OAAO,yDAAyD,EAClF8G,EAAU7C,IAAI,UAAW,OAAO,EAChCzE,qBACI,CACIC,OAAQ,mCACZ,EACA,CACIsH,QAAS,IACTC,QAAS,EACTtH,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACrC7B,IAAIwI,EAAiBlB,eAAemB,gCACpCzI,IAAIgJ,EAAWR,EAAeS,cAc9B,GAZsB,UAAlB,OAAOvH,GACPA,EAAOwH,eAAe,SAAS,GAC/BxH,EAAOwH,eAAe,cAAc,GACpCxH,EAAOwH,eAAe,WAAW,GACjCxH,EAAOwH,eAAe,cAAc,GACpCxH,EAAOwH,eAAe,WAAW,GACjCxH,EAAOwH,eAAe,aAAa,GACP,UAA5B,OAAOxH,EAAOyH,WACdzH,EAAOyH,UAAUD,eAAe,UAAU,GAC1CxH,EAAOyH,UAAUD,eAAe,OAAO,GACvCxH,EAAOyH,UAAUD,eAAe,UAAU,GAEzBxH,EAAO0H,QAAS,CACjC,GAAI1H,EAAO2H,aAAc,CACrBrJ,IAAIsJ,EAAc,GACdC,EAAqB,GACzBvJ,IAAIwJ,EAAiBhB,EAAeiB,aAqB9BC,GAlBFJ,EADA5H,EAAOiI,UACOnB,EAAeoB,kBAEfpB,EAAeqB,gBAI7BN,EADuB,IAAvB7H,EAAOoI,YACctB,EAAeuB,aAEfvB,EAAea,aAGxCtH,OAAO,mDAAmD,EAAEiI,KAAKtI,EAAOyH,UAAUc,QAAQ,EAC1FlI,OAAO,gDAAgD,EAAEiI,KAAKtI,EAAOyH,UAAUe,KAAK,EACpFnI,OAAO,mDAAmD,EAAEiI,KAAKtI,EAAOyH,UAAUgB,QAAQ,EAC1FpI,OAAO,oDAAoD,EAAEiI,KAAKV,CAAW,EAC7EvH,OAAO,gDAAgD,EAAEiI,KAAKT,CAAkB,EAChFxH,OAAO,uDAAuD,EAAEiI,KAAKR,CAAc,EACnFzH,OAAO,iDAAiD,EAAEiE,IAAI,UAAW,OAAO,EACvDjE,OAAO,+CAA+C,GAK/E,OAJA2H,EAAiBU,KAAK,WAAY,CAAA,CAAI,EACtCV,EAAiB1D,IAAI,QAAS,qBAAqB,EACnD0D,EAAiB1D,IAAI,aAAc,SAAS,EAF5C0D,KAGAb,EAAU7C,IAAI,UAAW,MAAM,CAEnC,CAC+B,CAAC,IAAxBtE,EAAOoI,YACPd,EAAWR,EAAe6B,mBACI,CAAC,IAAxB3I,EAAOoI,YACdd,EAAWR,EAAe8B,uBACI,CAAC,IAAxB5I,EAAOoI,YACdd,EAAWR,EAAe+B,YACI,CAAC,IAAxB7I,EAAOoI,cACdd,EAAWR,EAAegC,cAGtC,CACA3B,EAAU7C,IAAI,UAAW,MAAM,EAC/BjB,eAAeC,OAASgE,EACxBjE,eAAeE,KAAK,CACxB,EACAwF,YAAa,SAASC,GAClB7B,EAAU7C,IAAI,UAAW,MAAM,EAC/BjB,eAAeC,OAAS0F,EACxB3F,eAAeE,KAAK,CACxB,CACJ,CACJ,CACJ,CAp8BAlD,OAAO3C,QAAQ,EAAEuL,MAAM,WAEfvL,SAAS2D,uBAAuB,sBAAsB,EAAE,IACuC,QAA3F6H,iBAAiBxL,SAAS2D,uBAAuB,sBAAsB,EAAE,EAAE,EAAE8H,WAC7E9I,OAAO,kBAAkB,EAAEiE,IAAI,aAAc,OAAO,EAK5DjE,OAAO,mBAAmB,EAAE2E,GAAG,QAAS,SAASlB,GAC7CA,EAAEvB,eAAe,EACjBlC,OAAO+I,IAAI,EAAE7I,KAAK,EAClBF,OAAO,gCAAgC,EAAEgJ,IAAIhJ,OAAO,gCAAgC,EAAEqI,KAAK,KAAK,CAAC,EACjGrI,OAAO,oCAAoC,EAAEiE,IAAI,UAAW,QAAQ,CACxE,CAAC,EAKDjE,OAAQ3C,QAAS,EAAEsH,GAAG,QAAS,0CAA2C,WACtE3E,OAAO,oBAAoB,EAAElB,OAAO,EACpCb,IAAIgL,EAAiBjJ,OAAO,kBAAmBA,OAAO,kCAAkC,CAAC,EAGzF,GAFwBA,OAAO,uCAAuC,EACpDiE,IAAI,eAAgB,SAAS,EACL,KAAA,IAA9BgF,EAAerJ,KAAK,IAAI,EAChCsJ,QAAQC,IAAK,6CAA8C,MAD/D,CAIIvJ,EAAO,CACPwJ,YAAeH,EAAerJ,KAAK,IAAI,EACvCyJ,cAAiBJ,EAAerJ,KAAK,MAAM,EAC3C0J,SAAYL,EAAerJ,KAAK,UAAU,CAC9C,EACA3B,IAAIsL,EAASR,KACbvJ,qBACI,CAACC,OAAQ,4BAA6BG,KAAMA,CAAI,EAChD,CACImH,QAAS,KACTwC,OAAQA,EACRjF,QAAStE,OAAO,iEAAkE,EAClFgH,QAAS,CAAA,EACTtH,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACjCH,EAAO0H,SACPrH,OAAQ,6CAAmDL,EAAOC,KAAO,MAAO,EAC3E4J,YAAaxJ,OAAOuJ,CAAM,CAAE,EACjCvJ,OAAO,wDAAwD,EAAEuB,KAAK,GAAG,EACzEkI,WAAW,WACPzJ,OAAO,wDAAwD,EAAEE,KAAK,GAAG,CAC7E,EAAG,GAAI,EACP7C,SAASsB,iBAAiB,uBAAwB,SAAU8E,GACxDpG,SAASqM,SAASC,OAAO,CAC7B,CAAC,EACDF,WAAW,WACPzG,eAAe4G,MAAM,CACzB,EAAG,GAAI,GAEP5J,OAAQ,2CAAiDL,EAAOC,KAAO,MAAO,EACzE4J,YAAaxJ,OAAOuJ,CAAM,CAAE,CAEzC,CACJ,CACJ,CAlCA,CAmCJ,CAAC,EAGDvJ,OAAQ3C,QAAS,EAAEsH,GAAG,QAAS,0CAA2C,WACtE3E,OAAO,oBAAoB,EAAElB,OAAO,EACpCb,IAAIgL,EAAiBjJ,OAAO,kBAAmBA,OAAO,kCAAkC,CAAC,EACrF6J,EAAoB7J,OAAO,uCAAuC,EACtE/B,IAAI2B,EAAO,GAEX,GADAiK,EAAkB5F,IAAI,eAAgB,SAAS,EACL,KAAA,IAA9BgF,EAAerJ,KAAK,IAAI,EAChCsJ,QAAQC,IAAK,6CAA8C,MAD/D,CAIA,GAAmC,iBAA9BF,EAAerJ,KAAK,IAAI,EAAuB,CAChD3B,IAAI6L,EAAeD,EAAkBb,IAAI,EACzC,GAAsB,KAAjBc,EAED,OADAD,KAAAA,EAAkB5F,IAAI,eAAgB,KAAK,EAG/CrE,EAAO,CACHyJ,cAAiBS,CACrB,CACJ,MACIlK,EAAO,CACHwJ,YAAeH,EAAerJ,KAAK,IAAI,CAC3C,EAEJ3B,IAAIsL,EAASR,KACbvJ,qBACI,CAACC,OAAQ,4BAA6BG,KAAMA,CAAI,EAChD,CACImH,QAAS,KACTwC,OAAQA,EACRjF,QAAStE,OAAO,iEAAkE,EAClFgH,QAAS,CAAA,EACTtH,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACjCH,EAAO0H,SACPrH,OAAQ,6CAAmDL,EAAOC,KAAO,MAAO,EAC3E4J,YAAaxJ,OAAOuJ,CAAM,CAAE,EACjCvJ,OAAO,wDAAwD,EAAEuB,KAAK,GAAG,EACzEkI,WAAW,WACPzJ,OAAO,wDAAwD,EAAEE,KAAK,GAAG,CAC7E,EAAG,GAAI,EACP7C,SAASsB,iBAAiB,uBAAwB,SAAU8E,GACxDpG,SAASqM,SAASC,OAAO,CAC7B,CAAC,EACDF,WAAW,WACPzG,eAAe4G,MAAM,CACzB,EAAG,GAAI,GAEP5J,OAAQ,2CAAiDL,EAAOC,KAAO,MAAO,EACzE4J,YAAaxJ,OAAOuJ,CAAM,CAAE,CAEzC,CACJ,CACJ,CA3CA,CA4CJ,CAAC,EAGDvJ,OAAQ3C,QAAS,EAAEsH,GAAG,QAAS,yCAA0C,WACrE1G,IAAIsL,EAASR,KACbvJ,qBACI,CAACC,OAAQ,0BAA0B,EACnC,CACIsH,QAAS,KACTwC,OAAQA,EACRjF,QAAStE,OAAO,gEAAiE,EACjFgH,QAAS,CAAA,EACTtH,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACjCH,EAAO0H,SACPrH,OAAQ,6CAAmDL,EAAOC,KAAO,MAAO,EAC3E4J,YAAaxJ,OAAOuJ,CAAM,CAAE,EACjCvJ,OAAO,uDAAuD,EAAEuB,KAAK,GAAG,EACxEkI,WAAW,WACPzJ,OAAO,uDAAuD,EAAEE,KAAK,GAAG,CAC5E,EAAG,GAAI,EACP7C,SAASsB,iBAAiB,uBAAwB,SAAU8E,GACxDpG,SAASqM,SAASC,OAAO,CAC7B,CAAC,EACDF,WAAW,WACPzG,eAAe4G,MAAM,CACzB,EAAG,GAAI,GAEP5J,OAAQ,2CAAiDL,EAAOC,KAAO,MAAO,EACzE4J,YAAaxJ,OAAOuJ,CAAM,CAAE,CAEzC,CACJ,CACJ,CACJ,CAAC,EAGDvJ,OAAO,qBAAqB,EAAE2E,GAAG,QAAS,WACtCnF,qBACI,CAACC,OAAQ,YAAY,EACrB,CACIsH,QAAS,KACTwC,OAAQlM,SAASwD,eAAe,oBAAqB,EACrDyD,QAAStE,OAAO,6CAA8C,EAC9DN,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACrCE,OAAO,oCAAoC,EAAEuB,KAAK,GAAG,EACrDkI,WAAW,WACPzJ,OAAO,oCAAoC,EAAEE,KAAK,GAAG,CACzD,EAAG,GAAI,EACHP,EAAOgK,SACFpE,eAAewE,aAChB/J,OAAO,mBAAmB,EAAEE,KAAK,GAAG,EACpCF,OAAO,sBAAsB,EAAEuB,KAAK,GAAG,EACvCkI,WAAW,WACPpM,SAASqM,SAASC,OAAO,CAC7B,EAAG,GAAI,GAEPtM,SAASqM,SAASC,OAAO,EAGrC,CACJ,CACJ,CACJ,CAAC,EAEIpE,eAAewE,aAChB/J,OAAO,qBAAqB,EAAEqD,MAAM,EAGxCrD,OAAO3C,QAAQ,EAAEsH,GAAG,QAAS,0CAA2C,WAEpErB,6BADA0G,KAAOhK,OAAO+I,IAAI,EACiBiB,KAAK3B,KAAK,SAAS,CAAC,CAC3D,CAAC,GAEGrI,OAAO,yBAAyB,EAAEC,QAAUD,OAAO,yBAAyB,EAAEC,SAC9EZ,iBAAiB,EAGrBW,OAAO3C,QAAQ,EAAEsH,GAAG,SAAU,mCAAoC,WAE3B,iBADd3E,OAAO,kBAAmB+I,IAAI,EAC/BnJ,KAAK,IAAI,EACzBI,OAAO+I,IAAI,EAAEpF,OAAO,EAAEA,OAAO,EAAEsG,KAAK,uCAAuC,EAAE1I,KAAK,EAElFvB,OAAO+I,IAAI,EAAEpF,OAAO,EAAEA,OAAO,EAAEsG,KAAK,uCAAuC,EAAE/J,KAAK,CAE1F,CAAC,EAEDkF,wBAAwB,EACxBnH,IAAIiM,EACJjF,OAAOtG,iBAAiB,SAAU,WAC9BwL,aAAaD,CAAa,EAC1BA,EAAgBT,WAAW,WACvBrE,wBAAwB,CAC5B,EAAG,EAAE,EACLR,4BAA4B,CAChC,CAAC,EACD5E,OAAO,oBAAoB,EAAE2E,GAAG,QAASS,uBAAuB,EAMhEpF,OAAO,6BAA6B,EAAE2E,GAAG,QAAS,SAASlB,GACvDA,EAAEvB,eAAe,EAEjBjE,IAAImM,EAAQpK,OAAO+I,IAAI,EACnBsB,EAAoBrK,OAAO,sBAAsB,EACjDsK,EAAeD,EAAkBpC,KAAK,EAE1CmC,EAAMG,YAAY,QAAQ,EAEtBH,EAAMvG,SAAS,QAAQ,GACvBuG,EAAMnC,KAAKmC,EAAMxK,KAAK,WAAW,CAAC,EAClCyK,EAAkBhC,KAAK,kBAAmB,MAAM,EAChDgC,EAAkB1F,GAAG,UAAW,SAASlB,GACtB,UAAXA,EAAE+G,MACF/G,EAAEvB,eAAe,CAEzB,CAAC,EACDmI,EAAkB1F,GAAG,QAAS,SAASlB,GACf,oBAAhBA,EAAEgH,WACFhH,EAAEvB,eAAe,CAEzB,CAAC,IAED1C,qBACI,CACIC,OAAQ,6BACR6K,aAAcA,CAClB,EACA,CACIvD,QAAS,IACTrH,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GAChB4K,KAAAA,IAAjB/K,EAAOgL,OACP3K,OAAO,sBAAsB,EAAEiE,IAAI,eAAgB,KAAK,CAEhE,CACJ,CACJ,EAEAoG,EAAkBhC,KAAK,kBAAmB,OAAO,EACjD+B,EAAMnC,KAAKmC,EAAMxK,KAAK,cAAc,CAAC,EAE7C,CAAC,EAKDI,OAAO,uBAAuB,EAAE2E,GAAG,QAAS,WACxC1G,IAAI2M,EAAe5K,OAAO+I,IAAI,EAAEC,IAAI,EAEhC6B,GADJ7K,OAAO,0CAA0C,EAAE8D,IAAI,OAAO,EAChC,KAAjB8G,GAAoE,OAA7CA,EAAaE,MAAM,oBAAoB,GAC3E9K,OAAO,6BAA6B,EAAEE,KAAK,EAC3CF,OAAO,mBAAmB,EAAEE,KAAK,EACjCF,OAAO,kCAAkC,EAAEE,KAAK,EAC3B,KAAjB0K,GACA5K,OAAO,+CAA+C,EAAEE,KAAK,EACzDF,OAAO,6BAA6B,EAAEC,QACtCD,OAAO,sCAAsC,EAAEuB,KAAK,IAGxDvB,OAAO,+CAA+C,EAAEuB,KAAK,EAC7DvB,OAAO,sCAAsC,EAAEE,KAAK,EAChD2K,GACA7K,OAAO,0CAA0C,EAAE2E,GAAG,QAClD,SAASlB,GACLA,EAAEvB,eAAe,EACjBlC,OAAO,6BAA6B,EAAEuB,KAAK,EAC3CwE,sBAAsB,uBAAwB,CAAC,CACnD,CACJ,EAGZ,CAAC,EAEI/F,OAAO,uBAAuB,EAAEgJ,IAAI,GAAKzD,eAAeC,WACzDxF,OAAO,sCAAsC,EAAEE,KAAK,EAMlDqF,eAAeC,WAAcD,eAAeE,YAC9CzF,OAAO,6CAA6C,EAAE2E,GAAG,QACrD,SAASlB,GACLA,EAAEvB,eAAe,EACZlC,OAAO,uBAAuB,EAAEC,QACjCD,OAAQ,kKAES,EAAEwJ,YAAaxJ,OAAO,qBAAqB,CAAE,EAElE+F,sBAAsB,uBAAwB,CAAC,EAC/CA,sBAAsB,qBAAsB,CAAC,EAC7C/F,OAAO,sCAAsC,EAAEuB,KAAK,CACxD,CACJ,EAMJvB,OAAO,iCAAiC,EAAEqD,MAAM,SAASI,GACrDA,EAAEvB,eAAe,EAEjB,IAAMqH,EAASvJ,OAAO+I,IAAI,EAEpBgC,EAAiB9N,GAAG+N,MAAM,CAC5BC,QAAS,CACL5I,KAAM,OACV,EACA6I,SAAU,CAAA,CACd,CAAC,EAEDH,EAAepG,GAAG,SAAU,WACxB,IAAMwG,EAAQJ,EAAetI,MAAM,EAAE2I,IAAI,WAAW,EAAEC,MAAM,EAAEC,OAAO,EAErE/B,EAAO5F,OAAO,EAAEtC,KAAK,EAAEgH,KAAM,MAAO8C,EAAMI,GAAI,EAC9CvL,OAAO,wBAAwB,EAAEgJ,IAAKmC,EAAMpJ,EAAG,CACnD,CAAC,EAEDgJ,EAAe7H,KAAK,CACxB,CAAC,EAKDlD,OAAO,iCAAiC,EAAEqD,MAAM,SAASI,GACrDA,EAAEvB,eAAe,EAEZ,CAAA,IAASiB,QAAS,OAAQ,IACrBqI,EAAMxL,OAAO+I,IAAI,EAAEpF,OAAO,EAAEtC,KAAK,EAAEzB,KAAK,KAAK,EACnDI,OAAO+I,IAAI,EAAEpF,OAAO,EAAEtC,KAAK,EAAEgH,KAAK,MAAOmD,CAAG,EAC5CxL,OAAO+I,IAAI,EAAE1H,KAAK,EAAEA,KAAK,EAAE2H,IAAI,EAAE,EAEzC,CAAC,EAEDhJ,OAAO,2CAA2C,EAAEqD,MAAM,SAASI,GAC/DA,EAAEvB,eAAe,EAEjBjE,IAAI2B,EAAO,CACXH,OAAc,4BADF,EAIRI,GAFJD,EAAK6L,OAASzL,OAAO+I,IAAI,EAAEnJ,KAAK,QAAQ,EAE3B,IACbC,EAAO0J,OAASlM,SAASwD,eAAe,8BAAgCjB,EAAK6L,MAAM,EACnF5L,EAAOmH,QAAU,CAAA,EAEjBnH,EAAOH,SAAW,WACdrC,SAASqM,SAASC,OAAO,CAC7B,EAEAnK,qBAAqBI,EAAMC,CAAM,CACrC,CAAC,EAEDG,OAAO,4CAA4C,EAAEqD,MAAM,SAASI,GAChEA,EAAEvB,eAAe,EAEjBjE,IAAI2B,EAAO,CACXH,OAAc,6BADF,EAIRI,GAFJD,EAAK6L,OAASzL,OAAO+I,IAAI,EAAEnJ,KAAK,QAAQ,EAE3B,IACbC,EAAO0J,OAASlM,SAASwD,eAAe,+BAAiCjB,EAAK6L,MAAM,EACpF5L,EAAOmH,QAAU,CAAA,EAEjBnH,EAAOH,SAAW,WACdrC,SAASqM,SAASC,OAAO,CAC7B,EAEAnK,qBAAqBI,EAAMC,CAAM,CACrC,CAAC,EAEDxC,SAASC,cAAc,mCAAmC,GAAGqB,iBAAiB,QAAS,KACnFtB,SAASC,cAAc,8BAA8B,EAAEC,MAAMC,QAAU,QACvEH,SAASC,cAAc,mCAAmC,EAAEC,MAAMC,QAAU,MAChF,CAAC,EAEDH,SAASC,cAAc,yCAAyC,GAAGqB,iBAAiB,QAAS,KACzFtB,SAASC,cAAc,8BAA8B,EAAEC,MAAMC,QAAU,OACvEH,SAASC,cAAc,mCAAmC,EAAEC,MAAMC,QAAU,OAChF,CAAC,EAGDO,uCAAuC,EAGvCgB,iCAAiC,EAE7BkG,OAAOyE,SAASgC,MAEhBvO,sBADe8H,OAAOyE,SAASgC,KAAKC,UAAU,CAAC,CACnB,EAIhC3L,OAAO,MAAM,EAAE2E,GAAG,QAAS,8CAA+C,SAASlB,GAC/EA,EAAEvB,eAAe,EACjB0J,eAAeC,QAAQ,iCAAkC,GAAG,EAC5D7L,OAAO,6BAA6B,EAAEE,KAAK,EAC3CF,OAAO,2BAA2B,EAAEuB,KAAK,CAC7C,CAAC,CACL,CAAC"} \ No newline at end of file +{"version":3,"file":"cleantalk-admin-settings-page.min.js","sources":["cleantalk-admin-settings-page.js"],"sourcesContent":["const {__} = wp.i18n;\njQuery(document).ready(function() {\n // Crunch for Right to Left direction languages\n if (document.getElementsByClassName('apbct_settings-title')[0]) {\n if (getComputedStyle(document.getElementsByClassName('apbct_settings-title')[0]).direction === 'rtl') {\n jQuery('.apbct_switchers').css('text-align', 'right');\n }\n }\n\n // Show/Hide access key\n jQuery('#apbct_showApiKey').on('click', function(e) {\n e.preventDefault();\n jQuery(this).hide();\n jQuery('.apbct_settings-field--api_key').val(jQuery('.apbct_settings-field--api_key').attr('key'));\n jQuery('.apbct_settings-field--api_key+div').css('display', 'inline');\n });\n\n /**\n * Validate apikey and hide get auto btn\n */\n jQuery( document ).on('click', '#apbct_settings_templates_import_button', function() {\n jQuery('#apbct-ajax-result').remove();\n let optionSelected = jQuery('option:selected', jQuery('#apbct_settings_templates_import'));\n let templateNameInput = jQuery('#apbct_settings_templates_import_name');\n templateNameInput.css('border-color', 'inherit');\n if ( typeof optionSelected.data('id') === 'undefined' ) {\n console.log( 'Attribute \"data-id\" not set for the option.' );\n return;\n }\n let data = {\n 'template_id': optionSelected.data('id'),\n 'template_name': optionSelected.data('name'),\n 'settings': optionSelected.data('settings'),\n };\n let button = this;\n apbct_admin_sendAJAX(\n {action: 'settings_templates_import', data: data},\n {\n timeout: 25000,\n button: button,\n spinner: jQuery('#apbct_settings_templates_import_button .apbct_preloader_button' ),\n notJson: true,\n callback: function(result, data, params, obj) {\n if (result.success) {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n jQuery('#apbct_settings_templates_import_button .apbct_success').show(300);\n setTimeout(function() {\n jQuery('#apbct_settings_templates_import_button .apbct_success').hide(300);\n }, 2000);\n document.addEventListener('cleantalkModalClosed', function( e ) {\n document.location.reload();\n });\n setTimeout(function() {\n cleantalkModal.close();\n }, 2000);\n } else {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n }\n },\n },\n );\n });\n\n // Export settings\n jQuery( document ).on('click', '#apbct_settings_templates_export_button', function() {\n jQuery('#apbct-ajax-result').remove();\n let optionSelected = jQuery('option:selected', jQuery('#apbct_settings_templates_export'));\n let templateNameInput = jQuery('#apbct_settings_templates_export_name');\n let data = {};\n templateNameInput.css('border-color', 'inherit');\n if ( typeof optionSelected.data('id') === 'undefined' ) {\n console.log( 'Attribute \"data-id\" not set for the option.' );\n return;\n }\n if ( optionSelected.data('id') === 'new_template' ) {\n let templateName = templateNameInput.val();\n if ( templateName === '' ) {\n templateNameInput.css('border-color', 'red');\n return;\n }\n data = {\n 'template_name': templateName,\n };\n } else {\n data = {\n 'template_id': optionSelected.data('id'),\n };\n }\n let button = this;\n apbct_admin_sendAJAX(\n {action: 'settings_templates_export', data: data},\n {\n timeout: 25000,\n button: button,\n spinner: jQuery('#apbct_settings_templates_export_button .apbct_preloader_button' ),\n notJson: true,\n callback: function(result, data, params, obj) {\n if (result.success) {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n jQuery('#apbct_settings_templates_export_button .apbct_success').show(300);\n setTimeout(function() {\n jQuery('#apbct_settings_templates_export_button .apbct_success').hide(300);\n }, 2000);\n document.addEventListener('cleantalkModalClosed', function( e ) {\n document.location.reload();\n });\n setTimeout(function() {\n cleantalkModal.close();\n }, 2000);\n } else {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n }\n },\n },\n );\n });\n\n // Reset settings\n jQuery( document ).on('click', '#apbct_settings_templates_reset_button', function() {\n let button = this;\n apbct_admin_sendAJAX(\n {action: 'settings_templates_reset'},\n {\n timeout: 25000,\n button: button,\n spinner: jQuery('#apbct_settings_templates_reset_button .apbct_preloader_button' ),\n notJson: true,\n callback: function(result, data, params, obj) {\n if (result.success) {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n jQuery('#apbct_settings_templates_reset_button .apbct_success').show(300);\n setTimeout(function() {\n jQuery('#apbct_settings_templates_reset_button .apbct_success').hide(300);\n }, 2000);\n document.addEventListener('cleantalkModalClosed', function( e ) {\n document.location.reload();\n });\n setTimeout(function() {\n cleantalkModal.close();\n }, 2000);\n } else {\n jQuery( '

' + result.data + '

' )\n .insertAfter( jQuery(button) );\n }\n },\n },\n );\n });\n\n // Sync button\n jQuery('#apbct_button__sync').on('click', function() {\n apbct_admin_sendAJAX(\n {action: 'apbct_sync'},\n {\n timeout: 25000,\n button: document.getElementById('apbct_button__sync' ),\n spinner: jQuery('#apbct_button__sync .apbct_preloader_button' ),\n callback: function(result, data, params, obj) {\n jQuery('#apbct_button__sync .apbct_success').show(300);\n setTimeout(function() {\n jQuery('#apbct_button__sync .apbct_success').hide(300);\n }, 2000);\n if (result.reload) {\n if ( ctSettingsPage.key_changed ) {\n jQuery('.key_changed_sync').hide(300);\n jQuery('.key_changed_success').show(300);\n setTimeout(function() {\n document.location.reload();\n }, 3000);\n } else {\n document.location.reload();\n }\n }\n },\n },\n );\n });\n\n if ( ctSettingsPage.key_changed ) {\n jQuery('#apbct_button__sync').click();\n }\n\n jQuery(document).on('click', '.apbct_settings-long_description---show', function() {\n self = jQuery(this);\n apbctSettingsShowDescription(self, self.attr('setting'));\n });\n\n if (jQuery('#cleantalk_notice_renew').length || jQuery('#cleantalk_notice_trial').length) {\n apbctBannerCheck();\n }\n\n jQuery(document).on('change', '#apbct_settings_templates_export', function() {\n let optionSelected = jQuery('option:selected', this);\n if ( optionSelected.data('id') === 'new_template' ) {\n jQuery(this).parent().parent().find('#apbct_settings_templates_export_name').show();\n } else {\n jQuery(this).parent().parent().find('#apbct_settings_templates_export_name').hide();\n }\n });\n\n apbctSaveButtonPosition();\n let debounceTimer;\n window.addEventListener('scroll', function() {\n clearTimeout(debounceTimer);\n debounceTimer = setTimeout(function() {\n apbctSaveButtonPosition();\n }, 50);\n apbctNavigationMenuPosition();\n });\n jQuery('#ct_adv_showhide a').on('click', apbctSaveButtonPosition);\n\n\n /**\n * Change cleantalk account email\n */\n jQuery('#apbct-change-account-email').on('click', function(e) {\n e.preventDefault();\n\n let $this = jQuery(this);\n let accountEmailField = jQuery('#apbct-account-email');\n let accountEmail = accountEmailField.text();\n\n $this.toggleClass('active');\n\n if ($this.hasClass('active')) {\n $this.text($this.data('save-text'));\n accountEmailField.attr('contenteditable', 'true');\n accountEmailField.on('keydown', function(e) {\n if (e.code === 'Enter') {\n e.preventDefault();\n }\n });\n accountEmailField.on('input', function(e) {\n if (e.inputType === 'insertParagraph') {\n e.preventDefault();\n }\n });\n } else {\n apbct_admin_sendAJAX(\n {\n action: 'apbct_update_account_email',\n accountEmail: accountEmail,\n },\n {\n timeout: 5000,\n callback: function(result, data, params, obj) {\n if (result.error !== undefined) {\n jQuery('#apbct-account-email').css('border-color', 'red');\n }\n },\n },\n );\n\n accountEmailField.attr('contenteditable', 'false');\n $this.text($this.data('default-text'));\n }\n });\n\n /**\n * Validate apkikey and hide get auto btn\n */\n jQuery('#apbct_setting_apikey').on('input', function() {\n let enteredValue = jQuery(this).val();\n jQuery('#apbct_settings__key_line__save_settings').off('click');\n let keyBad = enteredValue !== '' && enteredValue.match(/^[a-z\\d]{8,30}\\s*$/) === null;\n jQuery('#apbct_settings__key_is_bad').hide();\n jQuery('#apbct_showApiKey').hide();\n jQuery('#apbct_settings__account_name_ob').hide();\n if (enteredValue === '') {\n jQuery('#apbct_button__key_line__save_changes_wrapper').hide();\n if (jQuery('#apbct_button__get_key_auto').length) {\n jQuery('#apbct_button__get_key_auto__wrapper').show();\n }\n } else {\n jQuery('#apbct_button__key_line__save_changes_wrapper').show();\n jQuery('#apbct_button__get_key_auto__wrapper').hide();\n if (keyBad) {\n jQuery('#apbct_settings__key_line__save_settings').on('click',\n function(e) {\n e.preventDefault();\n jQuery('#apbct_settings__key_is_bad').show();\n apbctHighlightElement('apbct_setting_apikey', 3);\n },\n );\n }\n }\n });\n\n if ( jQuery('#apbct_setting_apikey').val() && ctSettingsPage.key_is_ok) {\n jQuery('#apbct_button__get_key_auto__wrapper').hide();\n }\n\n /**\n * Handle synchronization errors when key is no ok to force user check the key and restart the sync\n */\n if ( !ctSettingsPage.key_is_ok && !ctSettingsPage.ip_license ) {\n jQuery('button.cleantalk_link[value=\"save_changes\"]').on('click',\n function(e) {\n e.preventDefault();\n if (!jQuery('#sync_required_notice').length) {\n jQuery( '

' +\n 'Synchronization process failed. Please, check the acces key and restart the synch.' +\n '

' ).insertAfter( jQuery('#apbct_button__sync') );\n }\n apbctHighlightElement('apbct_setting_apikey', 3);\n apbctHighlightElement('apbct_button__sync', 3);\n jQuery('#apbct_button__get_key_auto__wrapper').show();\n },\n );\n }\n\n /**\n * Open WP gallery for adding custom logo\n */\n jQuery('#apbct-custom-logo-open-gallery').click(function(e) {\n e.preventDefault();\n\n const button = jQuery(this);\n\n const customUploader = wp.media({\n library: {\n type: 'image',\n },\n multiple: false,\n });\n\n customUploader.on('select', function() {\n const image = customUploader.state().get('selection').first().toJSON();\n\n button.parent().prev().attr( 'src', image.url );\n jQuery('#cleantalk_custom_logo').val( image.id );\n });\n\n customUploader.open();\n });\n\n /**\n * Remove selected logo\n */\n jQuery('#apbct-custom-logo-remove-image').click(function(e) {\n e.preventDefault();\n\n if ( true === confirm( 'Sure?' ) ) {\n const src = jQuery(this).parent().prev().data('src');\n jQuery(this).parent().prev().attr('src', src);\n jQuery(this).prev().prev().val('');\n }\n });\n\n jQuery('button[id*=\"apbct-action-adjust-change-\"]').click(function(e) {\n e.preventDefault();\n\n let data = {};\n data.action = 'apbct_action_adjust_change';\n data.adjust = jQuery(this).data('adjust');\n\n let params = {};\n params.button = document.getElementById('apbct-action-adjust-change-' + data.adjust);\n params.notJson = true;\n\n params.callback = function() {\n document.location.reload();\n };\n\n apbct_admin_sendAJAX(data, params);\n });\n\n jQuery('button[id*=\"apbct-action-adjust-reverse-\"]').click(function(e) {\n e.preventDefault();\n\n let data = {};\n data.action = 'apbct_action_adjust_reverse';\n data.adjust = jQuery(this).data('adjust');\n\n let params = {};\n params.button = document.getElementById('apbct-action-adjust-reverse-' + data.adjust);\n params.notJson = true;\n\n params.callback = function() {\n document.location.reload();\n };\n\n apbct_admin_sendAJAX(data, params);\n });\n\n document.querySelector('.apbct_hidden_section_nav_mob_btn')?.addEventListener('click', () => {\n document.querySelector('#apbct_hidden_section_nav ul').style.display = 'block';\n document.querySelector('.apbct_hidden_section_nav_mob_btn').style.display = 'none';\n });\n\n document.querySelector('.apbct_hidden_section_nav_mob_btn-close')?.addEventListener('click', () => {\n document.querySelector('#apbct_hidden_section_nav ul').style.display = 'none';\n document.querySelector('.apbct_hidden_section_nav_mob_btn').style.display = 'block';\n });\n\n // Hide/show EmailEncoder replacing text textarea\n apbctManageEmailEncoderCustomTextField();\n\n // Turn SpamFireWall on with Anti-Crawler\n apbctManageAntiCrawlerDependency();\n\n if (window.location.hash) {\n const anchor = window.location.hash.substring(1);\n handleAnchorDetection(anchor);\n }\n\n // Fullpage trial/renew banner dismiss handler\n jQuery('body').on('click', '.apbct-trial-renew-fullpage .notice-dismiss', function(e) {\n e.preventDefault();\n sessionStorage.setItem('apbct_trial_fullpage_dismissed', '1');\n jQuery('.apbct-trial-renew-fullpage').hide();\n jQuery('#apbct-settings-page-wrap').show();\n });\n});\n\n/**\n * Detect ancors and open advanced settings before scroll\n * @param {string} anchor\n */\nfunction handleAnchorDetection(anchor) {\n let advSettings = document.querySelector('#apbct_settings__advanced_settings');\n if ( 'none' === advSettings.style.display ) {\n apbctExceptedShowHide('apbct_settings__advanced_settings');\n }\n scrollToAnchor('#' + anchor);\n}\n\n/**\n * Scroll to the target element ID\n * @param {string} anchorId Anchor target element ID\n */\nfunction scrollToAnchor(anchorId) {\n const targetElement = document.querySelector(anchorId);\n if (targetElement) {\n targetElement.scrollIntoView({\n block: 'end',\n });\n }\n}\n\n/**\n * Hide/show EmailEncoder replacing text textarea\n */\nfunction apbctManageEmailEncoderCustomTextField() {\n const replacingText = document\n .querySelector('#apbct_setting_data__email_decoder_obfuscation_custom_text');\n let replacingTextWrapperSub;\n if (replacingText !== null) {\n replacingTextWrapperSub = typeof replacingText.parentElement !== 'undefined' ?\n replacingText.parentElement :\n null;\n }\n document.querySelectorAll('.apbct_setting---data__email_decoder_obfuscation_mode').forEach((elem) => {\n // visibility set on saved settings\n if (replacingTextWrapperSub && elem.checked && elem.value !== 'replace') {\n replacingTextWrapperSub.classList.add('hidden');\n }\n // visibility set on change\n elem.addEventListener('click', (event) => {\n if (typeof replacingTextWrapperSub !== 'undefined') {\n if (event.target.value === 'replace') {\n replacingTextWrapperSub.classList.remove('hidden');\n } else {\n replacingTextWrapperSub.classList.add('hidden');\n }\n }\n });\n });\n}\n\n/**\n * Anti-Crawler is an add-on to SFW, so check SpamFireWall on enabling Anti-Crawler\n */\nfunction apbctManageAntiCrawlerDependency() {\n const antiCrawler = document.querySelector('#apbct_setting_sfw__anti_crawler');\n const spamFireWall = document.querySelector('#apbct_setting_sfw__enabled');\n if (!antiCrawler || !spamFireWall) {\n return;\n }\n antiCrawler.addEventListener('change', () => {\n if (! antiCrawler.checked || spamFireWall.checked) {\n return;\n }\n spamFireWall.checked = true;\n const childrens = spamFireWall.getAttribute('apbct_children');\n if (childrens !== null) {\n apbctSettingsDependencies(childrens, 1);\n }\n });\n}\n\n/**\n * Checking current account status for renew notice\n */\nfunction apbctBannerCheck() {\n let bannerChecker = setInterval( function() {\n apbct_admin_sendAJAX(\n {action: 'apbct_settings__check_renew_banner'},\n {\n callback: function(result, data, params, obj) {\n if (result.close_renew_banner) {\n if (jQuery('#cleantalk_notice_renew').length) {\n jQuery('#cleantalk_notice_renew').hide('slow');\n }\n if (jQuery('#cleantalk_notice_trial').length) {\n jQuery('#cleantalk_notice_trial').hide('slow');\n }\n clearInterval(bannerChecker);\n }\n },\n },\n );\n }, 900000);\n}\n\n/**\n * Select elems like #{selector} or .{selector}\n * Selector passed in string separated by ,\n *\n * @param {string|array} elems\n * @return {*}\n */\nfunction apbctGetElems(elems) {\n elems = elems.split(',');\n for ( let i=0, len = elems.length, tmp; i < len; i++) {\n tmp = jQuery('#'+elems[i]);\n elems[i] = tmp.length === 0 ? jQuery('.'+elems[i]) : tmp;\n }\n return elems;\n}\n\n/**\n * Select elems like #{selector} or .{selector}\n * Selector could be passed in a string ( separated by comma ) or in array ( [ elem1, elem2, ... ] )\n *\n * @param {string|array} elems\n * @return {array}\n */\nfunction apbctGetElemsNative(elems) {\n // Make array from a string\n if (typeof elems === 'string') {\n elems = elems.split(',');\n }\n\n let out = [];\n\n elems.forEach(function(elem, i, arr) {\n // try to get elements with such IDs\n let tmp = document.getElementById(elem);\n if (tmp !== null) {\n out.push( tmp[key] );\n return;\n }\n\n // try to get elements with such class name\n // write each elem from collection to new element of output array\n tmp = document.getElementsByClassName(elem);\n if (tmp !== null && tmp.length !==0 ) {\n for (key in tmp) {\n if ( +key >= 0 ) {\n out.push( tmp[key] );\n }\n }\n }\n });\n\n return out;\n}\n\n/**\n * @param {string|array} elems\n */\nfunction apbctShowHideElem(elems) {\n elems = apbctGetElems(elems);\n for ( let i=0, len = elems.length; i < len; i++) {\n elems[i].each(function(i, elem) {\n elem = jQuery(elem);\n let label = elem.next('label') || elem.prev('label') || null;\n if (elem.is(':visible')) {\n elem.hide();\n if (label) label.hide();\n } else {\n elem.show();\n if (label) label.show();\n }\n });\n }\n}\n\n/**\n * @param {string|array} element\n */\nfunction apbctExceptedShowHide(element) { // eslint-disable-line no-unused-vars\n let toHide = [\n 'apbct_settings__dwpms_settings',\n 'apbct_settings__advanced_settings',\n 'trusted_and_affiliate__special_span',\n ];\n let index = toHide.indexOf(element);\n if (index !== -1) {\n toHide.splice(index, 1);\n }\n apbctShowHideElem(element);\n toHide.forEach((toHideElem) => {\n if (document.getElementById(toHideElem) && document.getElementById(toHideElem).style.display !== 'none') {\n apbctShowHideElem(toHideElem);\n }\n });\n}\n\n/**\n * @param {mixed} event\n * @param {string} id\n */\nfunction apbctShowRequiredGroups(event, id) { // eslint-disable-line no-unused-vars\n let required = document.getElementById('apbct_settings__dwpms_settings');\n if (required && required.style.display === 'none') {\n let originEvent = event;\n event.preventDefault();\n apbctShowHideElem('apbct_settings__dwpms_settings');\n document.getElementById(id).dispatchEvent(new originEvent.constructor(originEvent.type, originEvent));\n }\n}\n\n/**\n * Settings dependences. Switch|toggle depended elements state (disabled|enabled)\n * Recieve list of selectors ( without class mark (.) or id mark (#) )\n *\n * @param {string|array} ids\n * @param {int} enable\n */\nfunction apbctSettingsDependencies(ids, enable) { // eslint-disable-line no-unused-vars\n enable = ! isNaN(enable) ? enable : null;\n\n // Get elements\n let elems = apbctGetElemsNative( ids );\n\n elems.forEach(function(elem, i, arr) {\n let doDisable = function() {\n elem.setAttribute('disabled', 'disabled');\n };\n let doEnable = function() {\n elem.removeAttribute('disabled');\n };\n\n // Set defined state\n if (enable === null) {\n enable = elem.getAttribute('disabled') === null ? 0 : 1;\n }\n\n enable === 1 ? doEnable() : doDisable();\n\n if ( elem.getAttribute('apbct_children') !== null) {\n let state = apbctSettingsDependenciesGetState( elem ) && enable;\n if ( state !== null ) {\n apbctSettingsDependencies( elem.getAttribute('apbct_children'), state );\n }\n }\n });\n}\n\n/**\n * @param {HTMLElement} elem\n * @return {int|null}\n */\nfunction apbctSettingsDependenciesGetState(elem) { // eslint-disable-line no-unused-vars\n let state;\n\n switch ( elem.getAttribute( 'type' ) ) {\n case 'checkbox':\n state = +elem.checked;\n break;\n case 'radio':\n state = +(+elem.getAttribute('value') === 1);\n break;\n default:\n state = null;\n }\n\n return state;\n}\n\n/**\n * Warn user about cookie type change if cache solutions found in environment.\n * #Call inlined from SettingsField\n * @param {object} event\n */\nfunction onApbctCookieTypeChange(event) { // eslint-disable-line no-unused-vars\n const switchToMode = event?.target?.value?.toString() || null;\n if (\n switchToMode !== null &&\n (\n switchToMode === '1' || // cookies on\n switchToMode === '0' // cookies off\n )\n ) {\n cleantalkModal.loaded = false;\n cleantalkModal.open(false);\n cleantalkModal.confirm(\n __('Attention!', 'cleantalk-spam-protect'),\n (\n __(\n 'Cache-problem solutions detected in the environment. ',\n 'cleantalk-spam-protect',\n ) +\n __(\n 'Switching cookie mode to \\'On\\' or \\'Off\\' may affect filtering quality. ',\n 'cleantalk-spam-protect',\n ) +\n __('The recommended setting is \\'Auto\\'.', 'cleantalk-spam-protect')\n ),\n '',\n (decision)=>{\n decision === true && jQuery('#apbct_setting_data__set_cookies__Auto').click();\n },\n __('Set to \"Auto\"', 'cleantalk-spam-protect'),\n __('Confirm mode change', 'cleantalk-spam-protect'),\n );\n }\n}\n\n/**\n * @param {HTMLElement} label\n * @param {string} settingId\n */\nfunction apbctSettingsShowDescription(label, settingId) {\n let removeDescFunc = function(e) {\n const callerIsPopup = jQuery(e.target).parent('.apbct_long_desc').length != 0;\n const callerIsHideCross = jQuery(e.target).hasClass('apbct_long_desc__cancel');\n const descIsShown = jQuery('.apbct_long_desc__title').length > 0;\n if (descIsShown && !callerIsPopup || callerIsHideCross) {\n jQuery('.apbct_long_desc').remove();\n jQuery(document).off('click', removeDescFunc);\n }\n };\n\n label.after('
');\n let obj = jQuery('#apbct_long_desc__'+settingId);\n obj.append('')\n .append('
')\n .css({\n top: label.position().top - 5,\n left: label.position().left + 25,\n });\n\n\n apbct_admin_sendAJAX(\n {action: 'apbct_settings__get__long_description', setting_id: settingId},\n {\n spinner: obj.children('img'),\n callback: function(result, data, params, obj) {\n if (result && result.title && result.desc) {\n obj.empty()\n .append('
')\n .append('')\n .append('

'+result.title+'

')\n .append('

'+result.desc+'

');\n\n jQuery(document).on('click', removeDescFunc);\n }\n },\n },\n obj,\n );\n}\n\n/**\n * Set position for navigation menu\n * @return {void}\n */\nfunction apbctNavigationMenuPosition() {\n const navBlock = document.querySelector('#apbct_hidden_section_nav ul');\n const rightBtnSave = document.querySelector('#apbct_settings__button_section');\n if (!navBlock || !rightBtnSave) {\n return;\n }\n const scrollPosition = window.scrollY;\n const windowWidth = window.innerWidth;\n if (scrollPosition > 1000) {\n navBlock.style.position = 'fixed';\n rightBtnSave.style.position = 'fixed';\n } else {\n navBlock.style.position = 'static';\n rightBtnSave.style.position = 'static';\n }\n\n if (windowWidth < 768) {\n rightBtnSave.style.position = 'fixed';\n }\n}\n\n/**\n * Set position for save button, hide it if scrolled to the bottom\n * @return {void}\n */\nfunction apbctSaveButtonPosition() {\n if (\n document.getElementById('apbct_settings__before_advanced_settings') === null ||\n document.getElementById('apbct_settings__after_advanced_settings') === null ||\n document.getElementById('apbct_settings__button_section') === null ||\n document.getElementById('apbct_settings__advanced_settings') === null ||\n document.getElementById('apbct_hidden_section_nav') === null\n ) {\n return;\n }\n\n if (!ctSettingsPage.key_is_ok && !ctSettingsPage.ip_license) {\n jQuery('#apbct_settings__main_save_button').hide();\n return;\n }\n\n const additionalSaveButton =\n document.querySelector('#apbct_settings__button_section, cleantalk_link[value=\"save_changes\"]');\n if (!additionalSaveButton) {\n return;\n }\n\n const scrollPosition = window.scrollY;\n const documentHeight = document.documentElement.scrollHeight;\n const windowHeight = window.innerHeight;\n const threshold = 800;\n if (scrollPosition + windowHeight >= documentHeight - threshold) {\n additionalSaveButton.style.display = 'none';\n } else {\n additionalSaveButton.style.display = 'block';\n }\n\n const advSettingsBlock = document.getElementById('apbct_settings__advanced_settings');\n const mainSaveButton = document.getElementById('apbct_settings__block_main_save_button');\n if (!advSettingsBlock || !mainSaveButton) {\n return;\n }\n\n if (advSettingsBlock.style.display == 'none') {\n mainSaveButton.classList.remove('apbct_settings__position_main_save_button');\n } else {\n mainSaveButton.classList.add('apbct_settings__position_main_save_button');\n }\n}\n\n/**\n * Hightlights element\n *\n * @param {string} id\n * @param {int} times\n */\nfunction apbctHighlightElement(id, times) {\n times = times-1 || 0;\n let keyField = jQuery('#'+id);\n jQuery('html, body').animate({scrollTop: keyField.offset().top - 100}, 'slow');\n keyField.addClass('apbct_highlighted');\n keyField.animate({opacity: 0}, 400, 'linear', function() {\n keyField.animate({opacity: 1}, 400, 'linear', function() {\n if (times>0) {\n apbctHighlightElement(id, times);\n } else {\n keyField.removeClass('apbct_highlighted');\n }\n });\n });\n}\n\n/**\n * Open modal to create support user\n */\nfunction apbctCreateSupportUser() { // eslint-disable-line no-unused-vars\n const localTextArray = ctSettingsPage.support_user_creation_msg_array;\n cleantalkModal.loaded = false;\n cleantalkModal.open(false);\n cleantalkModal.confirm(\n localTextArray.confirm_header,\n localTextArray.confirm_text,\n '',\n apbctCreateSupportUserCallback,\n );\n}\n\n/**\n * Create support user\n */\nfunction apbctCreateSupportUserCallback() {\n const preloader = jQuery('#apbct_summary_and_support-create_user_button_preloader');\n preloader.css('display', 'block');\n apbct_admin_sendAJAX(\n {\n action: 'apbct_action__create_support_user',\n },\n {\n timeout: 10000,\n notJson: 1,\n callback: function(result, data, params, obj) {\n let localTextArray = ctSettingsPage.support_user_creation_msg_array;\n let popupMsg = localTextArray.default_error;\n const responseValid = (\n typeof result === 'object' &&\n result.hasOwnProperty('success') &&\n result.hasOwnProperty('user_created') &&\n result.hasOwnProperty('mail_sent') &&\n result.hasOwnProperty('cron_updated') &&\n result.hasOwnProperty('user_data') &&\n result.hasOwnProperty('result_code') &&\n typeof result.user_data === 'object' &&\n result.user_data.hasOwnProperty('username') &&\n result.user_data.hasOwnProperty('email') &&\n result.user_data.hasOwnProperty('password')\n );\n if (responseValid && result.success) {\n if (result.user_created) {\n let mailSentMsg = '';\n let successCreationMsg = '';\n let cronUpdatedMsg = localTextArray.cron_updated;\n\n if (result.mail_sent) {\n mailSentMsg = localTextArray.mail_sent_success;\n } else {\n mailSentMsg = localTextArray.mail_sent_error;\n }\n\n if (result.result_code === 0) {\n successCreationMsg = localTextArray.user_updated;\n } else {\n successCreationMsg = localTextArray.user_created;\n }\n\n jQuery('#apbct_summary_and_support-user_creation_username').text(result.user_data.username);\n jQuery('#apbct_summary_and_support-user_creation_email').text(result.user_data.email);\n jQuery('#apbct_summary_and_support-user_creation_password').text(result.user_data.password);\n jQuery('#apbct_summary_and_support-user_creation_mail_sent').text(mailSentMsg);\n jQuery('#apbct_summary_and_support-user_creation_title').text(successCreationMsg);\n jQuery('#apbct_summary_and_support-user_creation_cron_updated').text(cronUpdatedMsg);\n jQuery('.apbct_summary_and_support-user_creation_result').css('display', 'block');\n const createUserButton = jQuery('#apbct_summary_and_support-create_user_button');\n createUserButton.attr('disabled', true);\n createUserButton.css('color', 'rgba(93,89,86,0.55)');\n createUserButton.css('background', '#cccccc');\n preloader.css('display', 'none');\n return;\n } else {\n if (result.result_code === -2) {\n popupMsg = localTextArray.invalid_permission;\n } else if (result.result_code === -1) {\n popupMsg = localTextArray.unknown_creation_error;\n } else if (result.result_code === -4) {\n popupMsg = localTextArray.on_cooldown;\n } else if (result.result_code === -5) {\n popupMsg = localTextArray.email_is_busy;\n }\n }\n }\n preloader.css('display', 'none');\n cleantalkModal.loaded = popupMsg;\n cleantalkModal.open();\n },\n errorOutput: function(msg) {\n preloader.css('display', 'none');\n cleantalkModal.loaded = msg;\n cleantalkModal.open();\n },\n },\n );\n}\n"],"names":["__","wp","i18n","handleAnchorDetection","anchor","document","querySelector","style","display","apbctExceptedShowHide","scrollToAnchor","anchorId","targetElement","scrollIntoView","block","apbctManageEmailEncoderCustomTextField","replacingText","let","replacingTextWrapperSub","parentElement","querySelectorAll","forEach","elem","checked","value","classList","add","addEventListener","event","target","remove","apbctManageAntiCrawlerDependency","antiCrawler","spamFireWall","childrens","getAttribute","apbctSettingsDependencies","apbctBannerCheck","bannerChecker","setInterval","apbct_admin_sendAJAX","action","callback","result","data","params","obj","close_renew_banner","jQuery","length","hide","clearInterval","apbctGetElems","elems","i","len","split","tmp","apbctGetElemsNative","out","arr","getElementById","push","key","getElementsByClassName","apbctShowHideElem","each","label","next","prev","is","show","element","toHide","index","indexOf","splice","toHideElem","apbctShowRequiredGroups","id","required","originEvent","preventDefault","dispatchEvent","constructor","type","ids","enable","isNaN","state","removeAttribute","setAttribute","apbctSettingsDependenciesGetState","onApbctCookieTypeChange","switchToMode","toString","cleantalkModal","loaded","open","confirm","decision","click","apbctSettingsShowDescription","settingId","removeDescFunc","e","callerIsPopup","parent","callerIsHideCross","hasClass","off","after","append","css","top","position","left","setting_id","spinner","children","title","desc","empty","on","apbctNavigationMenuPosition","scrollPosition","windowWidth","navBlock","rightBtnSave","window","scrollY","innerWidth","apbctSaveButtonPosition","advSettingsBlock","mainSaveButton","ctSettingsPage","key_is_ok","ip_license","additionalSaveButton","documentHeight","documentElement","scrollHeight","innerHeight","apbctHighlightElement","times","keyField","animate","scrollTop","offset","addClass","opacity","removeClass","apbctCreateSupportUser","localTextArray","support_user_creation_msg_array","confirm_header","confirm_text","apbctCreateSupportUserCallback","preloader","timeout","notJson","popupMsg","default_error","hasOwnProperty","user_data","success","user_created","mailSentMsg","successCreationMsg","cronUpdatedMsg","cron_updated","createUserButton","mail_sent","mail_sent_success","mail_sent_error","result_code","user_updated","text","username","email","password","attr","invalid_permission","unknown_creation_error","on_cooldown","email_is_busy","errorOutput","msg","ready","getComputedStyle","direction","this","val","optionSelected","console","log","template_id","template_name","settings","button","insertAfter","setTimeout","location","reload","close","templateNameInput","templateName","key_changed","self","find","debounceTimer","clearTimeout","$this","accountEmailField","accountEmail","toggleClass","code","inputType","undefined","error","enteredValue","keyBad","match","customUploader","media","library","multiple","image","get","first","toJSON","url","src","adjust","hash","substring","sessionStorage","setItem"],"mappings":"AAAA,IAAOA,GAAMC,GAAGC,KAAP,GAwaT,SAASC,sBAAsBC,GAEtB,SADaC,SAASC,cAAc,oCAAoC,EACjDC,MAAMC,SAC9BC,sBAAsB,mCAAmC,EAE7DC,eAAe,IAAMN,CAAM,CAC/B,CAMA,SAASM,eAAeC,GACdC,EAAgBP,SAASC,cAAcK,CAAQ,EACjDC,GACAA,EAAcC,eAAe,CACzBC,MAAO,KACX,CAAC,CAET,CAKA,SAASC,yCACL,IAAMC,EAAgBX,SACjBC,cAAc,4DAA4D,EAC/EW,IAAIC,EACkB,OAAlBF,IACAE,EAAiE,KAAA,IAAhCF,EAAcG,cAC3CH,EAAcG,cACd,MAERd,SAASe,iBAAiB,uDAAuD,EAAEC,QAAQ,IAEnFH,GAA2BI,EAAKC,SAA0B,YAAfD,EAAKE,OAChDN,EAAwBO,UAAUC,IAAI,QAAQ,EAGlDJ,EAAKK,iBAAiB,QAAS,IACY,KAAA,IAA5BT,IACoB,YAAvBU,EAAMC,OAAOL,MACbN,EAAwBO,UAAUK,OAAO,QAAQ,EAEjDZ,EAAwBO,UAAUC,IAAI,QAAQ,EAG1D,CAAC,CACL,CAAC,CACL,CAKA,SAASK,mCACL,IAAMC,EAAc3B,SAASC,cAAc,kCAAkC,EACvE2B,EAAe5B,SAASC,cAAc,6BAA6B,EACpE0B,GAAgBC,GAGrBD,EAAYL,iBAAiB,SAAU,KACnC,IAIMO,EAJAF,EAAYT,SAAWU,CAAAA,EAAaV,UAG1CU,EAAaV,QAAU,CAAA,EAEL,QADZW,EAAYD,EAAaE,aAAa,gBAAgB,KAExDC,0BAA0BF,EAAW,CAAC,CAE9C,CAAC,CACL,CAKA,SAASG,mBACLpB,IAAIqB,EAAgBC,YAAa,WAC7BC,qBACI,CAACC,OAAQ,oCAAoC,EAC7C,CACIC,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACjCH,EAAOI,qBACHC,OAAO,yBAAyB,EAAEC,QAClCD,OAAO,yBAAyB,EAAEE,KAAK,MAAM,EAE7CF,OAAO,yBAAyB,EAAEC,QAClCD,OAAO,yBAAyB,EAAEE,KAAK,MAAM,EAEjDC,cAAcb,CAAa,EAEnC,CACJ,CACJ,CACJ,EAAG,GAAM,CACb,CASA,SAASc,cAAcC,GAEnB,IAAMpC,IAAIqC,EAAE,EAAGC,GADfF,EAAQA,EAAMG,MAAM,GAAG,GACIP,OAAQQ,EAAKH,EAAIC,EAAKD,CAAC,GAC9CG,EAAMT,OAAO,IAAIK,EAAMC,EAAE,EACzBD,EAAMC,GAAoB,IAAfG,EAAIR,OAAeD,OAAO,IAAIK,EAAMC,EAAE,EAAIG,EAEzD,OAAOJ,CACX,CASA,SAASK,oBAAoBL,GAEJ,UAAjB,OAAOA,IACPA,EAAQA,EAAMG,MAAM,GAAG,GAG3BvC,IAAI0C,EAAM,GAsBV,OApBAN,EAAMhC,QAAQ,SAASC,EAAMgC,EAAGM,GAE5B3C,IAAIwC,EAAMpD,SAASwD,eAAevC,CAAI,EACtC,GAAY,OAARmC,EACAE,EAAIG,KAAML,EAAIM,IAAK,OAOvB,GAAY,QADZN,EAAMpD,SAAS2D,uBAAuB1C,CAAI,IACR,IAAdmC,EAAIR,OACpB,IAAKc,OAAON,EACK,GAAR,CAACM,KACFJ,EAAIG,KAAML,EAAIM,IAAK,CAInC,CAAC,EAEMJ,CACX,CAKA,SAASM,kBAAkBZ,GAEvB,IAAMpC,IAAIqC,EAAE,EAAGC,GADfF,EAAQD,cAAcC,CAAK,GACAJ,OAAQK,EAAIC,EAAKD,CAAC,GACzCD,EAAMC,GAAGY,KAAK,SAASZ,EAAGhC,GAEtBL,IAAIkD,GADJ7C,EAAO0B,OAAO1B,CAAI,GACD8C,KAAK,OAAO,GAAK9C,EAAK+C,KAAK,OAAO,GAAK,KACpD/C,EAAKgD,GAAG,UAAU,GAClBhD,EAAK4B,KAAK,EACNiB,GAAOA,EAAMjB,KAAK,IAEtB5B,EAAKiD,KAAK,EACNJ,GAAOA,EAAMI,KAAK,EAE9B,CAAC,CAET,CAKA,SAAS9D,sBAAsB+D,GAC3BvD,IAAIwD,EAAS,CACT,iCACA,oCACA,uCAEAC,EAAQD,EAAOE,QAAQH,CAAO,EACpB,CAAC,IAAXE,GACAD,EAAOG,OAAOF,EAAO,CAAC,EAE1BT,kBAAkBO,CAAO,EACzBC,EAAOpD,QAAQ,IACPhB,SAASwD,eAAegB,CAAU,GAA2D,SAAtDxE,SAASwD,eAAegB,CAAU,EAAEtE,MAAMC,SACjFyD,kBAAkBY,CAAU,CAEpC,CAAC,CACL,CAMA,SAASC,wBAAwBlD,EAAOmD,GACpC9D,IAAI+D,EAAW3E,SAASwD,eAAe,gCAAgC,EACnEmB,GAAuC,SAA3BA,EAASzE,MAAMC,WACvByE,EAAcrD,GACZsD,eAAe,EACrBjB,kBAAkB,gCAAgC,EAClD5D,SAASwD,eAAekB,CAAE,EAAEI,cAAc,IAAIF,EAAYG,YAAYH,EAAYI,KAAMJ,CAAW,CAAC,EAE5G,CASA,SAAS7C,0BAA0BkD,EAAKC,GACpCA,EAAWC,MAAMD,CAAM,EAAa,KAATA,EAGf7B,oBAAqB4B,CAAI,EAE/BjE,QAAQ,SAASC,EAAMgC,EAAGM,GAC5B3C,IAeQwE,EAHG,KAHPF,EADW,OAAXA,EAC2C,OAAlCjE,EAAKa,aAAa,UAAU,EAAa,EAAI,EAG1DoD,GARIjE,EAAKoE,gBAAgB,UAAU,EAH/BpE,EAAKqE,aAAa,WAAY,UAAU,EAaC,OAAxCrE,EAAKa,aAAa,gBAAgB,GAEpB,QADXsD,EAAQG,kCAAmCtE,CAAK,GAAKiE,IAErDnD,0BAA2Bd,EAAKa,aAAa,gBAAgB,EAAGsD,CAAM,CAGlF,CAAC,CACL,CAMA,SAASG,kCAAkCtE,GACvCL,IAAIwE,EAEJ,OAASnE,EAAKa,aAAc,MAAO,GACnC,IAAK,WACDsD,EAAQ,CAACnE,EAAKC,QACd,MACJ,IAAK,QACDkE,EAAQ,EAAkC,GAAhC,CAACnE,EAAKa,aAAa,OAAO,GACpC,MACJ,QACIsD,EAAQ,IACZ,CAEA,OAAOA,CACX,CAOA,SAASI,wBAAwBjE,GACvBkE,EAAelE,GAAOC,QAAQL,OAAOuE,SAAS,GAAK,KAEpC,OAAjBD,GAEqB,MAAjBA,GACiB,MAAjBA,IAGJE,eAAeC,OAAS,CAAA,EACxBD,eAAeE,KAAK,CAAA,CAAK,EACzBF,eAAeG,QACXnG,GAAG,aAAc,wBAAwB,EAErCA,GACI,wDACA,wBACJ,EACAA,GACI,wEACA,wBACJ,EACAA,GAAG,qCAAwC,wBAAwB,EAEvE,GACA,IACiB,CAAA,IAAboG,GAAqBpD,OAAO,wCAAwC,EAAEqD,MAAM,CAChF,EACArG,GAAG,gBAAiB,wBAAwB,EAC5CA,GAAG,sBAAuB,wBAAwB,CACtD,EAER,CAMA,SAASsG,6BAA6BnC,EAAOoC,GACpB,SAAjBC,EAA0BC,GAC1B,IAAMC,EAAsE,GAAtD1D,OAAOyD,EAAE5E,MAAM,EAAE8E,OAAO,kBAAkB,EAAE1D,OAC5D2D,EAAoB5D,OAAOyD,EAAE5E,MAAM,EAAEgF,SAAS,yBAAyB,GACd,EAA3C7D,OAAO,yBAAyB,EAAEC,QACnC,CAACyD,GAAiBE,KACjC5D,OAAO,kBAAkB,EAAElB,OAAO,EAClCkB,OAAO3C,QAAQ,EAAEyG,IAAI,QAASN,CAAc,EAEpD,CAEArC,EAAM4C,MAAM,6BAA8BR,EAAU,kCAAqC,EACzFtF,IAAI6B,EAAME,OAAO,qBAAqBuD,CAAS,EAC/CzD,EAAIkE,OAAO,gDAAkD,EACxDA,OAAO,4CAA8C,EACrDC,IAAI,CACDC,IAAK/C,EAAMgD,SAAS,EAAED,IAAM,EAC5BE,KAAMjD,EAAMgD,SAAS,EAAEC,KAAO,EAClC,CAAC,EAGL5E,qBACI,CAACC,OAAQ,wCAAyC4E,WAAYd,CAAS,EACvE,CACIe,QAASxE,EAAIyE,SAAS,KAAK,EAC3B7E,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACjCH,GAAUA,EAAO6E,OAAS7E,EAAO8E,OACjC3E,EAAI4E,MAAM,EACLV,OAAO,4CAA8C,EACrDA,OAAO,2DAA6D,EACpEA,OAAO,sCAAwCrE,EAAO6E,MAAM,OAAO,EACnER,OAAO,MAAMrE,EAAO8E,KAAK,MAAM,EAEpCzE,OAAO3C,QAAQ,EAAEsH,GAAG,QAASnB,CAAc,EAEnD,CACJ,EACA1D,CACJ,CACJ,CAMA,SAAS8E,8BACL,IAKMC,EACAC,EANAC,EAAW1H,SAASC,cAAc,8BAA8B,EAChE0H,EAAe3H,SAASC,cAAc,iCAAiC,EACxEyH,GAAaC,IAGZH,EAAiBI,OAAOC,QACxBJ,EAAcG,OAAOE,WACN,IAAjBN,GACAE,EAASxH,MAAM4G,SAAW,QAC1Ba,EAAazH,MAAM4G,SAAW,UAE9BY,EAASxH,MAAM4G,SAAW,SAC1Ba,EAAazH,MAAM4G,SAAW,UAG9BW,EAAc,OACdE,EAAazH,MAAM4G,SAAW,QAEtC,CAMA,SAASiB,0BACL,IAqBMP,EAUAQ,EACAC,EA/BsE,OAAxEjI,SAASwD,eAAe,0CAA0C,GACK,OAAvExD,SAASwD,eAAe,yCAAyC,GACH,OAA9DxD,SAASwD,eAAe,gCAAgC,GACS,OAAjExD,SAASwD,eAAe,mCAAmC,GACH,OAAxDxD,SAASwD,eAAe,0BAA0B,IAKjD0E,eAAeC,WAAcD,eAAeE,YAK3CC,EACFrI,SAASC,cAAc,uEAAuE,KAK5FuH,EAAiBI,OAAOC,QACxBS,EAAiBtI,SAASuI,gBAAgBC,aAI5CH,EAAqBnI,MAAMC,QADMmI,EADnB,KACdd,EAFiBI,OAAOa,YAGa,OAEA,QAGnCT,EAAmBhI,SAASwD,eAAe,mCAAmC,EAC9EyE,EAAiBjI,SAASwD,eAAe,wCAAwC,EAClFwE,IAAqBC,IAIY,QAAlCD,EAAiB9H,MAAMC,QACvB8H,EAAe7G,UAAUK,OAAO,2CAA2C,EAE3EwG,EAAe7G,UAAUC,IAAI,2CAA2C,GA7BxEsB,OAAO,mCAAmC,EAAEE,KAAK,EA+BzD,CAQA,SAAS6F,sBAAsBhE,EAAIiE,GAC/BA,EAAQA,EAAM,GAAK,EACnB/H,IAAIgI,EAAWjG,OAAO,IAAI+B,CAAE,EAC5B/B,OAAO,YAAY,EAAEkG,QAAQ,CAACC,UAAWF,EAASG,OAAO,EAAElC,IAAM,GAAG,EAAG,MAAM,EAC7E+B,EAASI,SAAS,mBAAmB,EACrCJ,EAASC,QAAQ,CAACI,QAAS,CAAC,EAAG,IAAK,SAAU,WAC1CL,EAASC,QAAQ,CAACI,QAAS,CAAC,EAAG,IAAK,SAAU,WAChC,EAANN,EACAD,sBAAsBhE,EAAIiE,CAAK,EAE/BC,EAASM,YAAY,mBAAmB,CAEhD,CAAC,CACL,CAAC,CACL,CAKA,SAASC,yBACL,IAAMC,EAAiBlB,eAAemB,gCACtC1D,eAAeC,OAAS,CAAA,EACxBD,eAAeE,KAAK,CAAA,CAAK,EACzBF,eAAeG,QACXsD,EAAeE,eACfF,EAAeG,aACf,GACAC,8BACJ,CACJ,CAKA,SAASA,iCACL,IAAMC,EAAY9G,OAAO,yDAAyD,EAClF8G,EAAU7C,IAAI,UAAW,OAAO,EAChCzE,qBACI,CACIC,OAAQ,mCACZ,EACA,CACIsH,QAAS,IACTC,QAAS,EACTtH,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACrC7B,IAAIwI,EAAiBlB,eAAemB,gCACpCzI,IAAIgJ,EAAWR,EAAeS,cAc9B,GAZsB,UAAlB,OAAOvH,GACPA,EAAOwH,eAAe,SAAS,GAC/BxH,EAAOwH,eAAe,cAAc,GACpCxH,EAAOwH,eAAe,WAAW,GACjCxH,EAAOwH,eAAe,cAAc,GACpCxH,EAAOwH,eAAe,WAAW,GACjCxH,EAAOwH,eAAe,aAAa,GACP,UAA5B,OAAOxH,EAAOyH,WACdzH,EAAOyH,UAAUD,eAAe,UAAU,GAC1CxH,EAAOyH,UAAUD,eAAe,OAAO,GACvCxH,EAAOyH,UAAUD,eAAe,UAAU,GAEzBxH,EAAO0H,QAAS,CACjC,GAAI1H,EAAO2H,aAAc,CACrBrJ,IAAIsJ,EAAc,GACdC,EAAqB,GACzBvJ,IAAIwJ,EAAiBhB,EAAeiB,aAqB9BC,GAlBFJ,EADA5H,EAAOiI,UACOnB,EAAeoB,kBAEfpB,EAAeqB,gBAI7BN,EADuB,IAAvB7H,EAAOoI,YACctB,EAAeuB,aAEfvB,EAAea,aAGxCtH,OAAO,mDAAmD,EAAEiI,KAAKtI,EAAOyH,UAAUc,QAAQ,EAC1FlI,OAAO,gDAAgD,EAAEiI,KAAKtI,EAAOyH,UAAUe,KAAK,EACpFnI,OAAO,mDAAmD,EAAEiI,KAAKtI,EAAOyH,UAAUgB,QAAQ,EAC1FpI,OAAO,oDAAoD,EAAEiI,KAAKV,CAAW,EAC7EvH,OAAO,gDAAgD,EAAEiI,KAAKT,CAAkB,EAChFxH,OAAO,uDAAuD,EAAEiI,KAAKR,CAAc,EACnFzH,OAAO,iDAAiD,EAAEiE,IAAI,UAAW,OAAO,EACvDjE,OAAO,+CAA+C,GAK/E,OAJA2H,EAAiBU,KAAK,WAAY,CAAA,CAAI,EACtCV,EAAiB1D,IAAI,QAAS,qBAAqB,EACnD0D,EAAiB1D,IAAI,aAAc,SAAS,EAF5C0D,KAGAb,EAAU7C,IAAI,UAAW,MAAM,CAEnC,CAC+B,CAAC,IAAxBtE,EAAOoI,YACPd,EAAWR,EAAe6B,mBACI,CAAC,IAAxB3I,EAAOoI,YACdd,EAAWR,EAAe8B,uBACI,CAAC,IAAxB5I,EAAOoI,YACdd,EAAWR,EAAe+B,YACI,CAAC,IAAxB7I,EAAOoI,cACdd,EAAWR,EAAegC,cAGtC,CACA3B,EAAU7C,IAAI,UAAW,MAAM,EAC/BjB,eAAeC,OAASgE,EACxBjE,eAAeE,KAAK,CACxB,EACAwF,YAAa,SAASC,GAClB7B,EAAU7C,IAAI,UAAW,MAAM,EAC/BjB,eAAeC,OAAS0F,EACxB3F,eAAeE,KAAK,CACxB,CACJ,CACJ,CACJ,CAp8BAlD,OAAO3C,QAAQ,EAAEuL,MAAM,WAEfvL,SAAS2D,uBAAuB,sBAAsB,EAAE,IACuC,QAA3F6H,iBAAiBxL,SAAS2D,uBAAuB,sBAAsB,EAAE,EAAE,EAAE8H,WAC7E9I,OAAO,kBAAkB,EAAEiE,IAAI,aAAc,OAAO,EAK5DjE,OAAO,mBAAmB,EAAE2E,GAAG,QAAS,SAASlB,GAC7CA,EAAEvB,eAAe,EACjBlC,OAAO+I,IAAI,EAAE7I,KAAK,EAClBF,OAAO,gCAAgC,EAAEgJ,IAAIhJ,OAAO,gCAAgC,EAAEqI,KAAK,KAAK,CAAC,EACjGrI,OAAO,oCAAoC,EAAEiE,IAAI,UAAW,QAAQ,CACxE,CAAC,EAKDjE,OAAQ3C,QAAS,EAAEsH,GAAG,QAAS,0CAA2C,WACtE3E,OAAO,oBAAoB,EAAElB,OAAO,EACpCb,IAAIgL,EAAiBjJ,OAAO,kBAAmBA,OAAO,kCAAkC,CAAC,EAGzF,GAFwBA,OAAO,uCAAuC,EACpDiE,IAAI,eAAgB,SAAS,EACL,KAAA,IAA9BgF,EAAerJ,KAAK,IAAI,EAChCsJ,QAAQC,IAAK,6CAA8C,MAD/D,CAIIvJ,EAAO,CACPwJ,YAAeH,EAAerJ,KAAK,IAAI,EACvCyJ,cAAiBJ,EAAerJ,KAAK,MAAM,EAC3C0J,SAAYL,EAAerJ,KAAK,UAAU,CAC9C,EACA3B,IAAIsL,EAASR,KACbvJ,qBACI,CAACC,OAAQ,4BAA6BG,KAAMA,CAAI,EAChD,CACImH,QAAS,KACTwC,OAAQA,EACRjF,QAAStE,OAAO,iEAAkE,EAClFgH,QAAS,CAAA,EACTtH,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACjCH,EAAO0H,SACPrH,OAAQ,6CAAmDL,EAAOC,KAAO,MAAO,EAC3E4J,YAAaxJ,OAAOuJ,CAAM,CAAE,EACjCvJ,OAAO,wDAAwD,EAAEuB,KAAK,GAAG,EACzEkI,WAAW,WACPzJ,OAAO,wDAAwD,EAAEE,KAAK,GAAG,CAC7E,EAAG,GAAI,EACP7C,SAASsB,iBAAiB,uBAAwB,SAAU8E,GACxDpG,SAASqM,SAASC,OAAO,CAC7B,CAAC,EACDF,WAAW,WACPzG,eAAe4G,MAAM,CACzB,EAAG,GAAI,GAEP5J,OAAQ,2CAAiDL,EAAOC,KAAO,MAAO,EACzE4J,YAAaxJ,OAAOuJ,CAAM,CAAE,CAEzC,CACJ,CACJ,CAlCA,CAmCJ,CAAC,EAGDvJ,OAAQ3C,QAAS,EAAEsH,GAAG,QAAS,0CAA2C,WACtE3E,OAAO,oBAAoB,EAAElB,OAAO,EACpCb,IAAIgL,EAAiBjJ,OAAO,kBAAmBA,OAAO,kCAAkC,CAAC,EACrF6J,EAAoB7J,OAAO,uCAAuC,EACtE/B,IAAI2B,EAAO,GAEX,GADAiK,EAAkB5F,IAAI,eAAgB,SAAS,EACL,KAAA,IAA9BgF,EAAerJ,KAAK,IAAI,EAChCsJ,QAAQC,IAAK,6CAA8C,MAD/D,CAIA,GAAmC,iBAA9BF,EAAerJ,KAAK,IAAI,EAAuB,CAChD3B,IAAI6L,EAAeD,EAAkBb,IAAI,EACzC,GAAsB,KAAjBc,EAED,OADAD,KAAAA,EAAkB5F,IAAI,eAAgB,KAAK,EAG/CrE,EAAO,CACHyJ,cAAiBS,CACrB,CACJ,MACIlK,EAAO,CACHwJ,YAAeH,EAAerJ,KAAK,IAAI,CAC3C,EAEJ3B,IAAIsL,EAASR,KACbvJ,qBACI,CAACC,OAAQ,4BAA6BG,KAAMA,CAAI,EAChD,CACImH,QAAS,KACTwC,OAAQA,EACRjF,QAAStE,OAAO,iEAAkE,EAClFgH,QAAS,CAAA,EACTtH,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACjCH,EAAO0H,SACPrH,OAAQ,6CAAmDL,EAAOC,KAAO,MAAO,EAC3E4J,YAAaxJ,OAAOuJ,CAAM,CAAE,EACjCvJ,OAAO,wDAAwD,EAAEuB,KAAK,GAAG,EACzEkI,WAAW,WACPzJ,OAAO,wDAAwD,EAAEE,KAAK,GAAG,CAC7E,EAAG,GAAI,EACP7C,SAASsB,iBAAiB,uBAAwB,SAAU8E,GACxDpG,SAASqM,SAASC,OAAO,CAC7B,CAAC,EACDF,WAAW,WACPzG,eAAe4G,MAAM,CACzB,EAAG,GAAI,GAEP5J,OAAQ,2CAAiDL,EAAOC,KAAO,MAAO,EACzE4J,YAAaxJ,OAAOuJ,CAAM,CAAE,CAEzC,CACJ,CACJ,CA3CA,CA4CJ,CAAC,EAGDvJ,OAAQ3C,QAAS,EAAEsH,GAAG,QAAS,yCAA0C,WACrE1G,IAAIsL,EAASR,KACbvJ,qBACI,CAACC,OAAQ,0BAA0B,EACnC,CACIsH,QAAS,KACTwC,OAAQA,EACRjF,QAAStE,OAAO,gEAAiE,EACjFgH,QAAS,CAAA,EACTtH,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACjCH,EAAO0H,SACPrH,OAAQ,6CAAmDL,EAAOC,KAAO,MAAO,EAC3E4J,YAAaxJ,OAAOuJ,CAAM,CAAE,EACjCvJ,OAAO,uDAAuD,EAAEuB,KAAK,GAAG,EACxEkI,WAAW,WACPzJ,OAAO,uDAAuD,EAAEE,KAAK,GAAG,CAC5E,EAAG,GAAI,EACP7C,SAASsB,iBAAiB,uBAAwB,SAAU8E,GACxDpG,SAASqM,SAASC,OAAO,CAC7B,CAAC,EACDF,WAAW,WACPzG,eAAe4G,MAAM,CACzB,EAAG,GAAI,GAEP5J,OAAQ,2CAAiDL,EAAOC,KAAO,MAAO,EACzE4J,YAAaxJ,OAAOuJ,CAAM,CAAE,CAEzC,CACJ,CACJ,CACJ,CAAC,EAGDvJ,OAAO,qBAAqB,EAAE2E,GAAG,QAAS,WACtCnF,qBACI,CAACC,OAAQ,YAAY,EACrB,CACIsH,QAAS,KACTwC,OAAQlM,SAASwD,eAAe,oBAAqB,EACrDyD,QAAStE,OAAO,6CAA8C,EAC9DN,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GACrCE,OAAO,oCAAoC,EAAEuB,KAAK,GAAG,EACrDkI,WAAW,WACPzJ,OAAO,oCAAoC,EAAEE,KAAK,GAAG,CACzD,EAAG,GAAI,EACHP,EAAOgK,SACFpE,eAAewE,aAChB/J,OAAO,mBAAmB,EAAEE,KAAK,GAAG,EACpCF,OAAO,sBAAsB,EAAEuB,KAAK,GAAG,EACvCkI,WAAW,WACPpM,SAASqM,SAASC,OAAO,CAC7B,EAAG,GAAI,GAEPtM,SAASqM,SAASC,OAAO,EAGrC,CACJ,CACJ,CACJ,CAAC,EAEIpE,eAAewE,aAChB/J,OAAO,qBAAqB,EAAEqD,MAAM,EAGxCrD,OAAO3C,QAAQ,EAAEsH,GAAG,QAAS,0CAA2C,WAEpErB,6BADA0G,KAAOhK,OAAO+I,IAAI,EACiBiB,KAAK3B,KAAK,SAAS,CAAC,CAC3D,CAAC,GAEGrI,OAAO,yBAAyB,EAAEC,QAAUD,OAAO,yBAAyB,EAAEC,SAC9EZ,iBAAiB,EAGrBW,OAAO3C,QAAQ,EAAEsH,GAAG,SAAU,mCAAoC,WAE3B,iBADd3E,OAAO,kBAAmB+I,IAAI,EAC/BnJ,KAAK,IAAI,EACzBI,OAAO+I,IAAI,EAAEpF,OAAO,EAAEA,OAAO,EAAEsG,KAAK,uCAAuC,EAAE1I,KAAK,EAElFvB,OAAO+I,IAAI,EAAEpF,OAAO,EAAEA,OAAO,EAAEsG,KAAK,uCAAuC,EAAE/J,KAAK,CAE1F,CAAC,EAEDkF,wBAAwB,EACxBnH,IAAIiM,EACJjF,OAAOtG,iBAAiB,SAAU,WAC9BwL,aAAaD,CAAa,EAC1BA,EAAgBT,WAAW,WACvBrE,wBAAwB,CAC5B,EAAG,EAAE,EACLR,4BAA4B,CAChC,CAAC,EACD5E,OAAO,oBAAoB,EAAE2E,GAAG,QAASS,uBAAuB,EAMhEpF,OAAO,6BAA6B,EAAE2E,GAAG,QAAS,SAASlB,GACvDA,EAAEvB,eAAe,EAEjBjE,IAAImM,EAAQpK,OAAO+I,IAAI,EACnBsB,EAAoBrK,OAAO,sBAAsB,EACjDsK,EAAeD,EAAkBpC,KAAK,EAE1CmC,EAAMG,YAAY,QAAQ,EAEtBH,EAAMvG,SAAS,QAAQ,GACvBuG,EAAMnC,KAAKmC,EAAMxK,KAAK,WAAW,CAAC,EAClCyK,EAAkBhC,KAAK,kBAAmB,MAAM,EAChDgC,EAAkB1F,GAAG,UAAW,SAASlB,GACtB,UAAXA,EAAE+G,MACF/G,EAAEvB,eAAe,CAEzB,CAAC,EACDmI,EAAkB1F,GAAG,QAAS,SAASlB,GACf,oBAAhBA,EAAEgH,WACFhH,EAAEvB,eAAe,CAEzB,CAAC,IAED1C,qBACI,CACIC,OAAQ,6BACR6K,aAAcA,CAClB,EACA,CACIvD,QAAS,IACTrH,SAAU,SAASC,EAAQC,EAAMC,EAAQC,GAChB4K,KAAAA,IAAjB/K,EAAOgL,OACP3K,OAAO,sBAAsB,EAAEiE,IAAI,eAAgB,KAAK,CAEhE,CACJ,CACJ,EAEAoG,EAAkBhC,KAAK,kBAAmB,OAAO,EACjD+B,EAAMnC,KAAKmC,EAAMxK,KAAK,cAAc,CAAC,EAE7C,CAAC,EAKDI,OAAO,uBAAuB,EAAE2E,GAAG,QAAS,WACxC1G,IAAI2M,EAAe5K,OAAO+I,IAAI,EAAEC,IAAI,EAEhC6B,GADJ7K,OAAO,0CAA0C,EAAE8D,IAAI,OAAO,EAChC,KAAjB8G,GAAoE,OAA7CA,EAAaE,MAAM,oBAAoB,GAC3E9K,OAAO,6BAA6B,EAAEE,KAAK,EAC3CF,OAAO,mBAAmB,EAAEE,KAAK,EACjCF,OAAO,kCAAkC,EAAEE,KAAK,EAC3B,KAAjB0K,GACA5K,OAAO,+CAA+C,EAAEE,KAAK,EACzDF,OAAO,6BAA6B,EAAEC,QACtCD,OAAO,sCAAsC,EAAEuB,KAAK,IAGxDvB,OAAO,+CAA+C,EAAEuB,KAAK,EAC7DvB,OAAO,sCAAsC,EAAEE,KAAK,EAChD2K,GACA7K,OAAO,0CAA0C,EAAE2E,GAAG,QAClD,SAASlB,GACLA,EAAEvB,eAAe,EACjBlC,OAAO,6BAA6B,EAAEuB,KAAK,EAC3CwE,sBAAsB,uBAAwB,CAAC,CACnD,CACJ,EAGZ,CAAC,EAEI/F,OAAO,uBAAuB,EAAEgJ,IAAI,GAAKzD,eAAeC,WACzDxF,OAAO,sCAAsC,EAAEE,KAAK,EAMlDqF,eAAeC,WAAcD,eAAeE,YAC9CzF,OAAO,6CAA6C,EAAE2E,GAAG,QACrD,SAASlB,GACLA,EAAEvB,eAAe,EACZlC,OAAO,uBAAuB,EAAEC,QACjCD,OAAQ,kKAES,EAAEwJ,YAAaxJ,OAAO,qBAAqB,CAAE,EAElE+F,sBAAsB,uBAAwB,CAAC,EAC/CA,sBAAsB,qBAAsB,CAAC,EAC7C/F,OAAO,sCAAsC,EAAEuB,KAAK,CACxD,CACJ,EAMJvB,OAAO,iCAAiC,EAAEqD,MAAM,SAASI,GACrDA,EAAEvB,eAAe,EAEjB,IAAMqH,EAASvJ,OAAO+I,IAAI,EAEpBgC,EAAiB9N,GAAG+N,MAAM,CAC5BC,QAAS,CACL5I,KAAM,OACV,EACA6I,SAAU,CAAA,CACd,CAAC,EAEDH,EAAepG,GAAG,SAAU,WACxB,IAAMwG,EAAQJ,EAAetI,MAAM,EAAE2I,IAAI,WAAW,EAAEC,MAAM,EAAEC,OAAO,EAErE/B,EAAO5F,OAAO,EAAEtC,KAAK,EAAEgH,KAAM,MAAO8C,EAAMI,GAAI,EAC9CvL,OAAO,wBAAwB,EAAEgJ,IAAKmC,EAAMpJ,EAAG,CACnD,CAAC,EAEDgJ,EAAe7H,KAAK,CACxB,CAAC,EAKDlD,OAAO,iCAAiC,EAAEqD,MAAM,SAASI,GACrDA,EAAEvB,eAAe,EAEZ,CAAA,IAASiB,QAAS,OAAQ,IACrBqI,EAAMxL,OAAO+I,IAAI,EAAEpF,OAAO,EAAEtC,KAAK,EAAEzB,KAAK,KAAK,EACnDI,OAAO+I,IAAI,EAAEpF,OAAO,EAAEtC,KAAK,EAAEgH,KAAK,MAAOmD,CAAG,EAC5CxL,OAAO+I,IAAI,EAAE1H,KAAK,EAAEA,KAAK,EAAE2H,IAAI,EAAE,EAEzC,CAAC,EAEDhJ,OAAO,2CAA2C,EAAEqD,MAAM,SAASI,GAC/DA,EAAEvB,eAAe,EAEjBjE,IAAI2B,EAAO,CACXH,OAAc,4BADF,EAIRI,GAFJD,EAAK6L,OAASzL,OAAO+I,IAAI,EAAEnJ,KAAK,QAAQ,EAE3B,IACbC,EAAO0J,OAASlM,SAASwD,eAAe,8BAAgCjB,EAAK6L,MAAM,EACnF5L,EAAOmH,QAAU,CAAA,EAEjBnH,EAAOH,SAAW,WACdrC,SAASqM,SAASC,OAAO,CAC7B,EAEAnK,qBAAqBI,EAAMC,CAAM,CACrC,CAAC,EAEDG,OAAO,4CAA4C,EAAEqD,MAAM,SAASI,GAChEA,EAAEvB,eAAe,EAEjBjE,IAAI2B,EAAO,CACXH,OAAc,6BADF,EAIRI,GAFJD,EAAK6L,OAASzL,OAAO+I,IAAI,EAAEnJ,KAAK,QAAQ,EAE3B,IACbC,EAAO0J,OAASlM,SAASwD,eAAe,+BAAiCjB,EAAK6L,MAAM,EACpF5L,EAAOmH,QAAU,CAAA,EAEjBnH,EAAOH,SAAW,WACdrC,SAASqM,SAASC,OAAO,CAC7B,EAEAnK,qBAAqBI,EAAMC,CAAM,CACrC,CAAC,EAEDxC,SAASC,cAAc,mCAAmC,GAAGqB,iBAAiB,QAAS,KACnFtB,SAASC,cAAc,8BAA8B,EAAEC,MAAMC,QAAU,QACvEH,SAASC,cAAc,mCAAmC,EAAEC,MAAMC,QAAU,MAChF,CAAC,EAEDH,SAASC,cAAc,yCAAyC,GAAGqB,iBAAiB,QAAS,KACzFtB,SAASC,cAAc,8BAA8B,EAAEC,MAAMC,QAAU,OACvEH,SAASC,cAAc,mCAAmC,EAAEC,MAAMC,QAAU,OAChF,CAAC,EAGDO,uCAAuC,EAGvCgB,iCAAiC,EAE7BkG,OAAOyE,SAASgC,MAEhBvO,sBADe8H,OAAOyE,SAASgC,KAAKC,UAAU,CAAC,CACnB,EAIhC3L,OAAO,MAAM,EAAE2E,GAAG,QAAS,8CAA+C,SAASlB,GAC/EA,EAAEvB,eAAe,EACjB0J,eAAeC,QAAQ,iCAAkC,GAAG,EAC5D7L,OAAO,6BAA6B,EAAEE,KAAK,EAC3CF,OAAO,2BAA2B,EAAEuB,KAAK,CAC7C,CAAC,CACL,CAAC"} \ No newline at end of file diff --git a/js/prebuild/apbct-public-bundle.js b/js/prebuild/apbct-public-bundle.js index f8fa38be9..9748b2dab 100644 --- a/js/prebuild/apbct-public-bundle.js +++ b/js/prebuild/apbct-public-bundle.js @@ -2253,7 +2253,7 @@ function ctSetCookie( cookies, value, expires='') { let listOfCookieNamesToForceAlt = [ 'ct_sfw_pass_key', 'ct_sfw_passed', - 'wordpress_apbct_antibot', + 'apbct_antibot', 'apbct_anticrawler_passed', 'apbct_bot_detector_exist', 'apbct_antiflood_passed', @@ -2642,6 +2642,15 @@ function getNoCookieData() { // eslint-disable-line no-unused-vars let noCookieDataLocal = apbctLocalStorage.getCleanTalkData(); let noCookieDataSession = apbctSessionStorage.getCleanTalkData(); let noCookieData = {...noCookieDataLocal, ...noCookieDataSession}; + + // Bot detector browser state is transferred with the hidden field on the NoCookie mode + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + noCookieData[browserState.key] = browserState.value; + } + } + noCookieData = JSON.stringify(noCookieData); return '_ct_no_cookie_data_' + btoa(unescape(encodeURIComponent(noCookieData))); @@ -2669,7 +2678,21 @@ function getCleanTalkStorageDataArray() { // eslint-disable-line no-unused-vars noCookieDataFromUserActivity = {collecting_user_activity_data: collectingUserActivityData}; } - return {...noCookieDataLocal, ...noCookieDataSession, ...noCookieDataTypo, ...noCookieDataFromUserActivity}; + let browserStateData = {}; + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + browserStateData[browserState.key] = browserState.value; + } + } + + return { + ...noCookieDataLocal, + ...noCookieDataSession, + ...noCookieDataTypo, + ...noCookieDataFromUserActivity, + ...browserStateData, + }; } /** @@ -3314,6 +3337,9 @@ class ApbctHandler { const eventTokenKey = useUnwrappedCleantalkKeys ? 'ct_bot_detector_event_token' : 'data%5Bct_bot_detector_event_token%5D'; + const browserStateKey = useUnwrappedCleantalkKeys ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; if (!( +ctPublic.bot_detector_enabled && @@ -3338,6 +3364,12 @@ class ApbctHandler { } } + const browserState = apbctGetBrowserStatePair(); + if (browserState && body.indexOf('apbct_browser_state') === -1) { + addidionalCleantalkData += '&' + browserStateKey + '=' + + encodeURIComponent(browserState.value); + } + body += addidionalCleantalkData; } @@ -3354,6 +3386,11 @@ class ApbctHandler { body.append('ct_bot_detector_event_token', eventToken); } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState && !body.has(browserState.key)) { + body.append(browserState.key, browserState.value); + } } if (isNeedToAddCleantalkDataCheckJsonData) { @@ -3391,6 +3428,22 @@ class ApbctHandler { } } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + try { + const bodyObj = JSON.parse(body); + if ( + bodyObj && typeof bodyObj === 'object' && + !Object.prototype.hasOwnProperty.call(bodyObj, browserState.key) + ) { + bodyObj[browserState.key] = browserState.value; + body = JSON.stringify(bodyObj); + } + } catch (e) { + // body is not JSON — leave as is + } + } } return originalSend.apply(this, [body]); @@ -3448,6 +3501,11 @@ class ApbctHandler { } else { args[1].body.append('ct_no_cookie_hidden_field', getNoCookieData()); } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + args[1].body.append(browserState.key, browserState.value); + } } } } catch (e) { @@ -3504,6 +3562,22 @@ class ApbctHandler { * @return {string|FormData} Modified body. */ const attachFieldsToBody = function(body, fieldPair = false) { + const fieldPairs = [fieldPair, apbctGetBrowserStatePair()]; + + for (const pair of fieldPairs) { + body = attachFieldPairToBody(body, pair); + } + + return body; + }; + + /** + * Attach a single key/value pair to fetch request body + * @param {string|FormData} body Fetch request data body. + * @param {object|bool} fieldPair Key value to inject. + * @return {string|FormData} Modified body. + */ + const attachFieldPairToBody = function(body, fieldPair = false) { if (fieldPair) { if (body instanceof FormData || typeof body.append === 'function') { body.append(fieldPair.key, fieldPair.value); @@ -3800,11 +3874,15 @@ class ApbctHandler { const batchPayload = JSON.parse(args[1].body); if (batchPayload.requests && Array.isArray(batchPayload.requests)) { const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); + const browserState = apbctGetBrowserStatePair(); for (const req of batchPayload.requests) { const isAddItem = req.path === '/wc/store/v1/cart/add-item'; if (isAddItem && req.body && fieldPair && fieldPair.key) { req.body[fieldPair.key] = fieldPair.value; } + if (isAddItem && req.body && browserState) { + req.body[browserState.key] = browserState.value; + } } args[1].body = JSON.stringify(batchPayload); } @@ -3828,289 +3906,1086 @@ class ApbctHandler { } /** - * Prepare jQuery.ajaxSetup to add nocookie data to the jQuery ajax request. + * Prepare jQuery.ajaxPrefilter to add CleanTalk data to jQuery ajax requests. * Notes: - * - Do it just once, the ajaxSetup.beforeSend will be overwritten for any calls. - * - Signs of forms need to be caught will be checked during ajaxSetup.settings.data process on send. + * - ajaxSetup.beforeSend is not used: a request can supply its own beforeSend and drop the default. + * - ajaxPrefilter runs for every jQuery ajax call after options are merged, so injection is guaranteed. + * - Form signs are checked on the request data/url at send time. * - Any sign of the form HTML of the caller is insignificant in this process. * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script * will work independing if jQuery is loaded by CleanTalk or not * @return {void} */ catchJqueryAjax() { - if ( typeof jQuery !== 'undefined') { - // this code run on base ajax rules - so do not work due scripts use it's own ajax object injections - if ( typeof jQuery.ajaxSetup === 'function' ) { - jQuery.ajaxSetup({ - beforeSend: function(xhr, settings) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(settings, 'ajaxSetup'); - if (sourceSign.found !== false) { - settings.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, settings.data); - } - }, - }); - } - // this code run on ANY ajax on ANY script queue status - // todo Probably move all ajaxSetup actions to ajaxPrefilter - if ( typeof jQuery.ajaxPrefilter === 'function' ) { - jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(options, 'ajaxPrefilter'); - if (sourceSign.found !== false) { - if (typeof options.data === 'string') { - options.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, options.data); - } - if ( - typeof options.data === 'object' && - typeof options.data.append === 'function' - ) { - options.data = handler.injectCleantalkDataToJQAjaxFormData(sourceSign, options.data); - } - } - }); - } + if ( typeof jQuery !== 'undefined' && typeof jQuery.ajaxPrefilter === 'function' ) { + jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { + const handler = new ApbctHandler(); + const sourceSign = handler.searchSignsForJQAjaxInjection(options, originalOptions); + if (sourceSign.found !== false) { + options.data = handler.injectCleantalkDataToJQAjax( + sourceSign, + handler.getJQAjaxPayloadForInject(options, originalOptions), + options, + ); + } + }); } } /** - * Search for sign within AJAX data to do inject CleanTalk data. - * @param {object} ajaxObject Ajax object. - * @param {string} catchOn Function should be catched on. - * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + * jQuery.param() on URLSearchParams/FormData can collapse options.data to "". + * Sign search already falls back to originalOptions; inject must use that payload too. + * @param {object} options + * @param {object=} originalOptions + * @return {*} */ - searchSignsForJQAjaxInjection(ajaxObject, catchOn = 'ajaxSetup') { - let sourceSign = { - 'found': false, - 'keepUnwrapped': false, - 'attachVisibleFieldsData': false, - }; - // on ajaxSetup - if (catchOn === 'ajaxSetup') { - // settings data is string (important!) - if ( typeof ajaxObject.data === 'string' ) { - if ( - ajaxObject.data.indexOf('action=fl_builder_subscribe_form_submit') !== -1 - ) { - sourceSign.found = 'fl_builder_subscribe_form_submit'; - } - if ( - ajaxObject.data.indexOf('twt_cc_signup') !== -1 - ) { - sourceSign.found = 'twt_cc_signup'; - } - if ( - ajaxObject.data.indexOf('action=mailpoet') !== -1 - ) { - sourceSign.found = 'action=mailpoet'; - sourceSign.attachVisibleFieldsData = true; - } - - if ( - ajaxObject.data.indexOf('action=user_registration') !== -1 && - ajaxObject.data.indexOf('ur_frontend_form_nonce') !== -1 - ) { - sourceSign.found = 'action=user_registration'; - } - - if (ajaxObject.data.indexOf('action=happyforms_message') !== -1) { - sourceSign.found = 'action=happyforms_message'; - } - - if ( - ajaxObject.data.indexOf('action=new_activity_comment') !== -1 - ) { - sourceSign.found = 'action=new_activity_comment'; - } - if ( - ajaxObject.data.indexOf('action=wwlc_create_user') !== -1 - ) { - sourceSign.found = 'action=wwlc_create_user'; - } - if ( - ajaxObject.data.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 - ) { - sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=drplus_signup') !== -1 - ) { - sourceSign.found = 'action=drplus_signup'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=bt_cc') !== -1 - ) { - sourceSign.found = 'action=bt_cc'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=wpr_form_builder_email') !== -1 - ) { - sourceSign.found = 'action=wpr_form_builder_email'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=nf_ajax_submit') !== -1 - ) { - sourceSign.found = 'action=nf_ajax_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=uael_register_user') !== -1 && - ctPublic.data__cookies_type === 'none' - ) { - sourceSign.found = 'action=uael_register_user'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=SQBSubmitQuizAjax') !== -1 - ) { - sourceSign.found = 'action=SQBSubmitQuizAjax'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=user_registration_user_form_submit') !== -1 - ) { - sourceSign.found = 'action=user_registration_user_form_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - } - // wooocommerce add to cart is based on URL - if ( typeof ajaxObject.url === 'string' ) { - if (ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1) { - sourceSign.found = 'wc-ajax=add_to_cart'; - } - } + getJQAjaxPayloadForInject(options, originalOptions) { + const current = options && options.data; + const original = originalOptions && originalOptions.data; + if ( this.jqAjaxPayloadWasCollapsed(current, original) ) { + return original; } + return current; + } - // on ajaxPrefilter - if (catchOn === 'ajaxPrefilter') { - if (typeof ajaxObject.data === 'string') { - if (ajaxObject.data.indexOf('action=bloom_subscribe') !== -1) { - sourceSign.found = 'action=bloom_subscribe'; - sourceSign.keepUnwrapped = true; - } - } + /** + * @param {*} current + * @param {*} original + * @return {boolean} + */ + jqAjaxPayloadWasCollapsed(current, original) { + if ( original === null || typeof original === 'undefined' ) { + return false; + } + if ( current === original ) { + return false; + } + const currentEmpty = current === '' || current === null || typeof current === 'undefined'; + if ( !currentEmpty ) { + return false; + } + if ( typeof original === 'string' ) { + return original !== ''; + } + return this.isJQAjaxFormData(original) || + this.isJQAjaxURLSearchParams(original) || + this.isJQAjaxPlainObjectOrArray(original); + } - if ( - typeof ajaxObject.data === 'object' && - ajaxObject.data !== null && - typeof ajaxObject.data.get === 'function' - ) { - if (ajaxObject.data.get('action') === 'pafe_ajax_form_builder') { - sourceSign.found = 'action=pafe_ajax_form_builder'; - sourceSign.keepUnwrapped = true; - } - } + /** + * Normalize jQuery ajax data to a query string for sign search. + * Objects and serializeArray are read structurally so search never calls jQuery.param. + * Also reads known sign fields from the URL (IE11 FormData cannot be enumerated). + * @param {object} ajaxObject Ajax options object. + * @return {string} + */ + getJQAjaxDataAsString(ajaxObject) { + if ( !ajaxObject || typeof ajaxObject !== 'object' ) { + return ''; + } + let fromData = ''; + if ( typeof ajaxObject.data === 'string' ) { + fromData = ajaxObject.data; + } else if ( this.isJQAjaxPlainObjectOrArray(ajaxObject.data) ) { + fromData = this.getStructuredJQAjaxSignString(ajaxObject.data); + } else if ( this.isJQAjaxURLSearchParams(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } else if ( this.isJQAjaxFormData(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } + // Native IE11 FormData is write-only (no get/forEach/entries). Signs then come from the URL. + const fromUrl = this.collectKnownSignStringFromUrl(ajaxObject.url); + if ( fromData && fromUrl ) { + return fromData + '&' + fromUrl; } + return fromData || fromUrl; + } - return sourceSign; + /** + * Build a sign string from top-level fields without serializing the whole payload. + * @param {object|Array} data + * @return {string} + */ + getStructuredJQAjaxSignString(data) { + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return this.getSerializeArraySignString(data); + } + const parts = []; + const action = this.getPlainObjectSignField(data, 'action'); + if ( typeof action === 'string' && action !== '' ) { + parts.push('action=' + action); + } + const nonce = this.getPlainObjectSignField(data, 'ur_frontend_form_nonce'); + if ( nonce !== null ) { + parts.push('ur_frontend_form_nonce=' + nonce); + } + if ( this.plainObjectHasTwtCcSignup(data) ) { + parts.push('twt_cc_signup=1'); + } + return parts.join('&'); } /** - * Injecting CleanTalk data to ajax data FormData object. - * @param {object} sourceSign - * @param {object} ajaxDataFormData - * @return {object} + * Read action/nonce from top-level, data[key], or nested data.key. + * @param {object} data + * @param {string} key + * @return {string|number|null} */ - injectCleantalkDataToJQAjaxFormData(sourceSign, ajaxDataFormData) { + getPlainObjectSignField(data, key) { + if ( !data || typeof data !== 'object' ) { + return null; + } + if ( this.isJQAjaxScalarSignValue(data[key]) ) { + return data[key]; + } + const bracketKey = 'data[' + key + ']'; + if ( this.isJQAjaxScalarSignValue(data[bracketKey]) ) { + return data[bracketKey]; + } if ( - typeof sourceSign !== 'object' || - typeof ajaxDataFormData !== 'object' || - !(ajaxDataFormData instanceof FormData) + data.data && + typeof data.data === 'object' && + Object.prototype.toString.call(data.data) !== '[object Array]' && + this.isJQAjaxScalarSignValue(data.data[key]) ) { - return ajaxDataFormData; + return data.data[key]; } + return null; + } - try { - // Event token + /** + * @param {*} value + * @return {boolean} + */ + isJQAjaxScalarSignValue(value) { + return typeof value === 'string' || typeof value === 'number'; + } + + /** + * @param {object} data + * @param {number=} depth + * @return {boolean} + */ + plainObjectHasTwtCcSignup(data, depth) { + if ( !data || typeof data !== 'object' ) { + return false; + } + if ( typeof depth === 'undefined' ) { + depth = 0; + } + if ( depth > 2 ) { + return false; + } + for ( const key in data ) { + if ( !Object.prototype.hasOwnProperty.call(data, key) ) { + continue; + } + const normalizedKey = this.unwrapJQAjaxFormDataKey(key); + if ( normalizedKey === 'twt_cc_signup' || key.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + const value = data[key]; + if ( typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1 ) { + return true; + } if ( - +ctPublic.bot_detector_enabled && - apbctLocalStorage.get('bot_detector_event_token') + value && + typeof value === 'object' && + Object.prototype.toString.call(value) !== '[object Array]' ) { - const token = this.toolGetEventToken(); - if (token) { - if (sourceSign.keepUnwrapped) { - ajaxDataFormData.append('ct_bot_detector_event_token', token); - } else { - ajaxDataFormData.append('data[ct_bot_detector_event_token]', token); - } - } - } else { - // No cookie data - let noCookieData = getNoCookieData(); - if (noCookieData) { - if (sourceSign.keepUnwrapped) { - ajaxDataFormData.append('ct_no_cookie_hidden_field', noCookieData); - } else { - ajaxDataFormData.append('data[ct_no_cookie_hidden_field]', noCookieData); - } + if ( this.plainObjectHasTwtCcSignup(value, depth + 1) ) { + return true; } } + } + return false; + } - // Visible fields - if (sourceSign.attachVisibleFieldsData) { - let visibleFieldsSearchResult = false; - const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); - if (extractor) { - // Try to find form_id in FormData to find form container and - // collect visible fields only inside it - let formId = null; - for (let pair of ajaxDataFormData.entries()) { - if (pair[0] === 'form_id' || pair[0] === 'data[form_id]') { - formId = pair[1]; - break; - } - } - let container = null; - if (formId && typeof formId === 'string') { - // Sanitize formId to prevent selector injection - const sanitizedFormId = formId.replace(/["\\]/g, ''); - // First, try to find by id - container = document.getElementById(sanitizedFormId); - // If not found, try to find by data-id - if (!container) { - container = document.querySelector('[data-id="' + sanitizedFormId + '"]'); - } - } - if (container) { - // Collect all input, select, textarea inside the container - const fields = container.querySelectorAll('input, select, textarea'); - // Use collectVisibleFields, passing an object with elements - const visibleFieldsObj = new ApbctAttachData().collectVisibleFields({elements: fields}); - visibleFieldsSearchResult = JSON.stringify(visibleFieldsObj); - } - } - if (typeof visibleFieldsSearchResult === 'string' && visibleFieldsSearchResult.length > 0) { - ajaxDataFormData.append('apbct_visible_fields', visibleFieldsSearchResult); - } + /** + * @param {Array} entries + * @return {string} + */ + getSerializeArraySignString(entries) { + const parts = []; + for ( let i = 0; i < entries.length; i++ ) { + const entry = entries[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + continue; + } + const value = entry.value; + const normalizedKey = this.unwrapJQAjaxFormDataKey(entry.name); + if ( this.isJQAjaxKnownSignField(normalizedKey, value) ) { + parts.push(normalizedKey + '=' + value); } - } catch (e) { - // Silently fail to not break the original request } - - return ajaxDataFormData; + return parts.join('&'); } /** - * Injecting CleanTalk data to ajax data string. - * @param {object} sourceSign Object of found sign to intercept. - * @param {string} ajaxDataString Original data string from ajax object. - * @return {string} + * True for serializeArray payloads, including an empty array. + * @param {Array} data + * @return {boolean} */ - injectCleantalkDataToJQAjaxString(sourceSign, ajaxDataString) { - // something wrong with incoming data - if (typeof sourceSign !== 'object' || typeof ajaxDataString !== 'string') { - return ajaxDataString; + isJQAjaxSerializeArray(data) { + if ( Object.prototype.toString.call(data) !== '[object Array]' ) { + return false; + } + for ( let i = 0; i < data.length; i++ ) { + const entry = data[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + return false; + } + } + return true; + } + + /** + * Cross-realm URLSearchParams (instanceof fails across windows). + * @param {*} data + * @return {boolean} + */ + isJQAjaxURLSearchParams(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object URLSearchParams]' ) { + return true; + } + if ( tag === '[object FormData]' ) { + return false; + } + return typeof data.sort === 'function' && typeof data.get === 'function'; + } + + /** + * Cross-realm FormData, including common polyfills. + * @param {*} data + * @return {boolean} + */ + isJQAjaxFormData(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) || this.isJQAjaxURLSearchParams(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object FormData]' ) { + return true; + } + if ( tag === '[object Headers]' || typeof data.getSetCookie === 'function' ) { + return false; + } + return typeof data.forEach === 'function' || + typeof data.get === 'function' || + typeof data.entries === 'function'; + } + + /** + * Collect only known sign fields from FormData / URLSearchParams. + * Unwrap data[action] so later action=... checks match. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + collectKnownSignStringFromKeyValueBag(bag) { + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' ) { + return; + } + const valueAsString = String(value); + const normalizedKey = unwrapKey(key); + if ( + knownKeys[normalizedKey] || + valueAsString.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + valueAsString); + } + }); + if ( collected ) { + return parts.join('&'); + } + if ( typeof bag.get !== 'function' ) { + return ''; + } + const keysToProbe = [ + 'action', + 'ur_frontend_form_nonce', + 'twt_cc_signup', + ]; + const getParts = []; + for ( let i = 0; i < keysToProbe.length; i++ ) { + const key = keysToProbe[i]; + const value = this.getFormDataScalarValue(bag, [key, 'data[' + key + ']']); + if ( value !== null ) { + getParts.push(key + '=' + value); + } + } + return getParts.join('&'); + } + + /** + * Known sign fields from a request URL query. IE11-safe (no URLSearchParams). + * @param {string} url + * @return {string} + */ + collectKnownSignStringFromUrl(url) { + if ( typeof url !== 'string' || url === '' ) { + return ''; + } + const queryIndex = url.indexOf('?'); + if ( queryIndex === -1 || queryIndex === url.length - 1 ) { + return ''; + } + const hashIndex = url.indexOf('#', queryIndex); + const query = hashIndex === -1 ? + url.slice(queryIndex + 1) : + url.slice(queryIndex + 1, hashIndex); + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const pairs = query.split('&'); + for ( let i = 0; i < pairs.length; i++ ) { + const pair = pairs[i]; + if ( !pair ) { + continue; + } + const eq = pair.indexOf('='); + let rawKey = eq === -1 ? pair : pair.slice(0, eq); + let rawValue = eq === -1 ? '' : pair.slice(eq + 1); + try { + rawKey = decodeURIComponent(rawKey.replace(/\+/g, ' ')); + rawValue = decodeURIComponent(rawValue.replace(/\+/g, ' ')); + } catch (e) { + continue; + } + const normalizedKey = unwrapKey(rawKey); + if ( + knownKeys[normalizedKey] || + rawValue.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + rawValue); + } + } + return parts.join('&'); + } + + /** + * Walk FormData/URLSearchParams via forEach, then entries() for polyfills that only have an iterator. + * @param {FormData|URLSearchParams} bag + * @param {Function} callback + * @return {boolean} + */ + forEachJQAjaxKeyValueBag(bag, callback) { + if ( typeof bag.forEach === 'function' ) { + try { + bag.forEach(callback); + return true; + } catch (e) { + // Fall through to entries(). + } + } + if ( typeof bag.entries !== 'function' ) { + return false; + } + try { + const iterator = bag.entries(); + if ( !iterator || typeof iterator.next !== 'function' ) { + return false; + } + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + callback(pair[1], pair[0]); + } + step = iterator.next(); + } + return true; + } catch (e) { + return false; + } + } + + /** + * @return {Object} + */ + getJQAjaxKnownSignKeys() { + const knownKeys = Object.create(null); + knownKeys.action = true; + knownKeys.ur_frontend_form_nonce = true; + knownKeys.twt_cc_signup = true; + return knownKeys; + } + + /** + * @param {string} normalizedKey + * @param {*} value + * @return {boolean} + */ + isJQAjaxKnownSignField(normalizedKey, value) { + if ( + normalizedKey === 'action' || + normalizedKey === 'ur_frontend_form_nonce' || + normalizedKey === 'twt_cc_signup' || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + return true; + } + return typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1; + } + + /** + * Treat data[action] as action for WP-style payloads. + * @param {string} key + * @return {string} + */ + unwrapJQAjaxFormDataKey(key) { + if ( typeof key !== 'string' ) { + return ''; + } + if ( key.length > 6 && key.indexOf('data[') === 0 && key.charAt(key.length - 1) === ']' ) { + return key.slice(5, -1); + } + return key; + } + + /** + * @param {FormData} formData + * @param {Array.} keys + * @return {string|number|null} + */ + getFormDataScalarValue(formData, keys) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && (typeof value === 'string' || typeof value === 'number') ) { + return value; + } + } + return null; + } + + /** + * True for arrays and plain objects that jQuery.param can serialize safely. + * @param {*} data + * @return {boolean} + */ + isJQAjaxPlainObjectOrArray(data) { + if ( data === null || typeof data !== 'object' ) { + return false; + } + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return true; + } + if ( typeof jQuery !== 'undefined' && typeof jQuery.isPlainObject === 'function' ) { + return jQuery.isPlainObject(data); + } + const proto = Object.getPrototypeOf(data); + return proto === Object.prototype || proto === null; + } + + /** + * Search for sign within AJAX data to do inject CleanTalk data. + * @param {object} ajaxObject Ajax object. + * @param {object=} originalOptions Original jQuery ajax options before merge. + * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + */ + searchSignsForJQAjaxInjection(ajaxObject, originalOptions) { + let sourceSign = { + 'found': false, + 'keepUnwrapped': false, + 'attachVisibleFieldsData': false, + }; + let dataString = this.getJQAjaxDataAsString(ajaxObject); + if ( !dataString && originalOptions && originalOptions !== ajaxObject ) { + dataString = this.getJQAjaxDataAsString(originalOptions); + } + + if ( dataString.indexOf('action=fl_builder_subscribe_form_submit') !== -1 ) { + sourceSign.found = 'fl_builder_subscribe_form_submit'; + } + if ( dataString.indexOf('twt_cc_signup') !== -1 ) { + sourceSign.found = 'twt_cc_signup'; + } + if ( dataString.indexOf('action=mailpoet') !== -1 ) { + sourceSign.found = 'action=mailpoet'; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=user_registration') !== -1 && + dataString.indexOf('ur_frontend_form_nonce') !== -1 + ) { + sourceSign.found = 'action=user_registration'; + } + if ( dataString.indexOf('action=happyforms_message') !== -1 ) { + sourceSign.found = 'action=happyforms_message'; + } + if ( dataString.indexOf('action=new_activity_comment') !== -1 ) { + sourceSign.found = 'action=new_activity_comment'; + } + if ( dataString.indexOf('action=wwlc_create_user') !== -1 ) { + sourceSign.found = 'action=wwlc_create_user'; + } + if ( dataString.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 ) { + sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=drplus_signup') !== -1 ) { + sourceSign.found = 'action=drplus_signup'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=bt_cc') !== -1 ) { + sourceSign.found = 'action=bt_cc'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=wpr_form_builder_email') !== -1 ) { + sourceSign.found = 'action=wpr_form_builder_email'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=nf_ajax_submit') !== -1 ) { + sourceSign.found = 'action=nf_ajax_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=uael_register_user') !== -1 && + ctPublic.data__cookies_type === 'none' + ) { + sourceSign.found = 'action=uael_register_user'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=SQBSubmitQuizAjax') !== -1 ) { + sourceSign.found = 'action=SQBSubmitQuizAjax'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=user_registration_user_form_submit') !== -1 ) { + sourceSign.found = 'action=user_registration_user_form_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=bloom_subscribe') !== -1 ) { + sourceSign.found = 'action=bloom_subscribe'; + sourceSign.keepUnwrapped = true; + } + if ( + this.isJQAjaxFormData(ajaxObject.data) && + typeof ajaxObject.data.get === 'function' && + ajaxObject.data.get('action') === 'pafe_ajax_form_builder' + ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } else if ( dataString.indexOf('action=pafe_ajax_form_builder') !== -1 ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } + + // woocommerce add to cart is based on URL + if ( typeof ajaxObject.url === 'string' && ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1 ) { + sourceSign.found = 'wc-ajax=add_to_cart'; + // GET/HEAD: PHP reads Get::get('ct_bot_detector_event_token'), not data[...]. + if ( this.isJQAjaxNoContentMethod(ajaxObject) ) { + sourceSign.keepUnwrapped = true; + } + } + + return sourceSign; + } + + /** + * Inject CleanTalk data into jQuery ajax payload of any supported type. + * @param {object} sourceSign + * @param {*} ajaxData + * @param {object=} ajaxOptions jQuery ajax options (traditional, processData, contentType). + * Keep URLSearchParams/objects when processData or contentType is false. + * URLSearchParams must also disable processData, or jQuery.param() later yields "". + * GET/HEAD never keep the original type: jQuery only puts string data on the URL. + * @return {*} + */ + injectCleantalkDataToJQAjax(sourceSign, ajaxData, ajaxOptions) { + const traditional = ajaxOptions && ajaxOptions.traditional; + const keepOriginalType = !this.isJQAjaxNoContentMethod(ajaxOptions) && !!(ajaxOptions && ( + ajaxOptions.processData === false || + ajaxOptions.contentType === false + )); + + if ( ajaxData === null || typeof ajaxData === 'undefined' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ''); + } + if ( typeof ajaxData === 'string' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData); + } + if ( this.isJQAjaxPlainObjectOrArray(ajaxData) ) { + if ( keepOriginalType ) { + if ( Object.prototype.toString.call(ajaxData) === '[object Array]' ) { + if ( this.isJQAjaxSerializeArray(ajaxData) ) { + return this.injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData); + } + return ajaxData; + } + return this.injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData); + } + try { + if ( typeof jQuery !== 'undefined' && typeof jQuery.param === 'function' ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + jQuery.param(ajaxData, traditional), + ); + } + } catch (e) { + return ajaxData; + } + return ajaxData; + } + if ( this.isJQAjaxURLSearchParams(ajaxData) ) { + if ( keepOriginalType ) { + this.preserveJQAjaxURLSearchParamsOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxKeyValue( + sourceSign, + this.cloneURLSearchParams(ajaxData), + ); + } + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData.toString()); + } + if ( this.isJQAjaxFormData(ajaxData) ) { + if ( this.isJQAjaxNoContentMethod(ajaxOptions) ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + this.serializeJQAjaxKeyValueBag(ajaxData), + ); + } + this.preserveJQAjaxFormDataOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxFormData( + sourceSign, + this.cloneFormData(ajaxData), + ); + } + return ajaxData; + } + + /** + * GET/HEAD have no body. Missing type is GET (jQuery default). + * @param {object=} ajaxOptions + * @return {boolean} + */ + isJQAjaxNoContentMethod(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return false; + } + const type = ajaxOptions.type || ajaxOptions.method; + if ( typeof type !== 'string' || type === '' ) { + return true; + } + const method = type.toUpperCase(); + return method === 'GET' || method === 'HEAD'; + } + + /** + * Collect CleanTalk fields to append to a key/value payload. + * @param {object} sourceSign + * @return {Array.>} + */ + getCleantalkJQAjaxFieldPairs(sourceSign) { + const pairs = []; + const wrapKey = function(key) { + return sourceSign.keepUnwrapped ? key : 'data[' + key + ']'; + }; + + if ( + +ctPublic.bot_detector_enabled && + apbctLocalStorage.get('bot_detector_event_token') + ) { + const token = this.toolGetEventToken(); + if ( token ) { + pairs.push([wrapKey('ct_bot_detector_event_token'), token]); + } + } else { + const noCookieData = getNoCookieData(); + if ( noCookieData ) { + pairs.push([wrapKey('ct_no_cookie_hidden_field'), noCookieData]); + } + } + + const browserState = apbctGetBrowserStatePair(); + if ( browserState ) { + const browserStateKey = sourceSign.keepUnwrapped ? + browserState.key : + 'data[' + browserState.key + ']'; + pairs.push([browserStateKey, browserState.value]); + } + + return pairs; + } + + /** + * jQuery.param(FormData) after the prefilter yields "". Keep the body as FormData. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxFormDataOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + ajaxOptions.contentType = false; + } + + /** + * jQuery.param(URLSearchParams) after the prefilter yields "". Keep the body as URLSearchParams. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxURLSearchParamsOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + } + + /** + * Read a FormData field via get(), forEach(), or entries(). + * Native IE11 FormData is write-only and cannot be read. + * @param {FormData} formData + * @param {Array.} keys + * @return {*} + */ + getFormDataField(formData, keys) { + if ( typeof formData.get === 'function' ) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && typeof value !== 'undefined' ) { + return value; + } + } + } + if ( typeof formData.forEach === 'function' ) { + let found = null; + formData.forEach(function(value, key) { + if ( found !== null ) { + return; + } + for ( let i = 0; i < keys.length; i++ ) { + if ( key === keys[i] ) { + found = value; + return; + } + } + }); + if ( found !== null ) { + return found; + } + } + if ( typeof formData.entries === 'function' ) { + try { + const iterator = formData.entries(); + if ( iterator && typeof iterator.next === 'function' ) { + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + for ( let i = 0; i < keys.length; i++ ) { + if ( pair[0] === keys[i] ) { + return pair[1]; + } + } + } + step = iterator.next(); + } + } + } catch (e) { + return null; + } + } + return null; + } + + /** + * Clone URLSearchParams so the caller's instance is not mutated. + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + cloneURLSearchParams(params) { + const serialized = typeof params.toString === 'function' ? params.toString() : ''; + if ( typeof params.constructor === 'function' && params.constructor !== Object ) { + try { + return new params.constructor(serialized); + } catch (e) { + // Fall through to the current-window constructor. + } + } + if ( typeof URLSearchParams === 'function' ) { + try { + return new URLSearchParams(serialized); + } catch (e) { + return params; + } + } + return params; + } + + /** + * Clone FormData when it can be enumerated (forEach or entries); otherwise reuse. + * @param {FormData} formData + * @return {FormData} + */ + cloneFormData(formData) { + try { + const clone = new FormData(); + const copied = this.forEachJQAjaxKeyValueBag(formData, function(value, key) { + clone.append(key, value); + }); + if ( copied ) { + return clone; + } + } catch (e) { + return formData; + } + return formData; + } + + /** + * Form-urlencoded string from FormData/URLSearchParams. Skip File/Blob values. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + serializeJQAjaxKeyValueBag(bag) { + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { + return; + } + parts.push(encodeURIComponent(String(key)) + '=' + encodeURIComponent(String(value))); + }); + if ( collected ) { + return parts.join('&'); + } + return ''; + } + + /** + * Inject CleanTalk fields into URLSearchParams without changing the payload type. + * @param {object} sourceSign + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + injectCleantalkDataToJQAjaxKeyValue(sourceSign, params) { + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + params.append(pairs[i][0], pairs[i][1]); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( extractor ) { + const extracted = extractor.extract(params.toString()); + if ( typeof extracted === 'string' ) { + params.append('apbct_visible_fields', extracted); + } + } + } + return params; + } + + /** + * Inject CleanTalk fields into a jQuery serializeArray payload. + * @param {object} sourceSign + * @param {Array} ajaxData + * @return {Array} + */ + injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData) { + const result = ajaxData.slice(); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result.push({ + name: pairs[i][0], + value: pairs[i][1], + }); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' + ) { + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.push({ + name: 'apbct_visible_fields', + value: extracted, + }); + } + } + } + return result; + } + + /** + * Inject CleanTalk fields into a plain object without changing the payload type. + * @param {object} sourceSign + * @param {object} ajaxData + * @return {object} + */ + injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData) { + const result = typeof jQuery !== 'undefined' && typeof jQuery.extend === 'function' ? + jQuery.extend({}, ajaxData) : + this.clonePlainObject(ajaxData); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result[pairs[i][0]] = pairs[i][1]; + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' + ) { + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.apbct_visible_fields = extracted; + } + } + } + return result; + } + + /** + * IE11-safe shallow copy of a plain object. + * @param {object} ajaxData + * @return {object} + */ + clonePlainObject(ajaxData) { + const result = {}; + for ( const key in ajaxData ) { + if ( Object.prototype.hasOwnProperty.call(ajaxData, key) ) { + result[key] = ajaxData[key]; + } + } + return result; + } + + /** + * Injecting CleanTalk data to ajax data FormData object. + * @param {object} sourceSign + * @param {object} ajaxDataFormData + * @return {object} + */ + injectCleantalkDataToJQAjaxFormData(sourceSign, ajaxDataFormData) { + if ( + typeof sourceSign !== 'object' || + !this.isJQAjaxFormData(ajaxDataFormData) + ) { + return ajaxDataFormData; + } + + try { + // Event token + if ( + +ctPublic.bot_detector_enabled && + apbctLocalStorage.get('bot_detector_event_token') + ) { + const token = this.toolGetEventToken(); + if (token) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append('ct_bot_detector_event_token', token); + } else { + ajaxDataFormData.append('data[ct_bot_detector_event_token]', token); + } + } + } else { + // No cookie data + let noCookieData = getNoCookieData(); + if (noCookieData) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append('ct_no_cookie_hidden_field', noCookieData); + } else { + ajaxDataFormData.append('data[ct_no_cookie_hidden_field]', noCookieData); + } + } + } + + // Bot detector browser state + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append(browserState.key, browserState.value); + } else { + ajaxDataFormData.append('data[' + browserState.key + ']', browserState.value); + } + } + + // Visible fields + if (sourceSign.attachVisibleFieldsData) { + let visibleFieldsSearchResult = false; + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if (extractor) { + // Try to find form_id in FormData to find form container and + // collect visible fields only inside it + const formId = this.getFormDataField( + ajaxDataFormData, + ['form_id', 'data[form_id]'], + ); + let container = null; + if (formId && typeof formId === 'string') { + // Sanitize formId to prevent selector injection + const sanitizedFormId = formId.replace(/["\\]/g, ''); + // First, try to find by id + container = document.getElementById(sanitizedFormId); + // If not found, try to find by data-id + if (!container) { + container = document.querySelector('[data-id="' + sanitizedFormId + '"]'); + } + } + if (container) { + // Collect all input, select, textarea inside the container + const fields = container.querySelectorAll('input, select, textarea'); + // Use collectVisibleFields, passing an object with elements + const visibleFieldsObj = new ApbctAttachData().collectVisibleFields({elements: fields}); + visibleFieldsSearchResult = JSON.stringify(visibleFieldsObj); + } + } + if (typeof visibleFieldsSearchResult === 'string' && visibleFieldsSearchResult.length > 0) { + ajaxDataFormData.append('apbct_visible_fields', visibleFieldsSearchResult); + } + } + } catch (e) { + // Silently fail to not break the original request + } + + return ajaxDataFormData; + } + + /** + * Injecting CleanTalk data to ajax data string. + * @param {object} sourceSign Object of found sign to intercept. + * @param {string} ajaxDataString Original data string from ajax object. + * @return {string} + */ + injectCleantalkDataToJQAjaxString(sourceSign, ajaxDataString) { + // something wrong with incoming data + if (typeof sourceSign !== 'object' || typeof ajaxDataString !== 'string') { + return ajaxDataString; + } + let eventToken = ''; + let noCookieData = ''; + let visibleFieldsString = ''; + let browserStateString = ''; + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + const browserStateKey = sourceSign.keepUnwrapped ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; + browserStateString = browserStateKey + '=' + encodeURIComponent(browserState.value) + '&'; } - let eventToken = ''; - let noCookieData = ''; - let visibleFieldsString = ''; if ( +ctPublic.bot_detector_enabled && @@ -4127,9 +5002,9 @@ class ApbctHandler { } else { noCookieData = getNoCookieData(); if (sourceSign.keepUnwrapped) { - noCookieData = 'ct_no_cookie_hidden_field=' + noCookieData + '&'; + noCookieData = 'ct_no_cookie_hidden_field=' + encodeURIComponent(noCookieData) + '&'; } else { - noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + noCookieData + '&'; + noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + encodeURIComponent(noCookieData) + '&'; } } @@ -4152,7 +5027,7 @@ class ApbctHandler { } } - return noCookieData + eventToken + visibleFieldsString + ajaxDataString; + return noCookieData + eventToken + browserStateString + visibleFieldsString + ajaxDataString; } /** @@ -4888,67 +5763,126 @@ if (document.readyState !== 'loading') { */ new ApbctHandler().cronFormsHandler(2000); -let botDetectorLogLastUpdate = 0; -let botDetectorLogEventTypesCollected = []; - -// bot_detector frontend_data log alt session saving cron -if ( - ctPublicFunctions.hasOwnProperty('bot_detector_enabled') && - +ctPublicFunctions.bot_detector_enabled && - ctPublicFunctions.hasOwnProperty('data__frontend_data_log_enabled') && - ctPublicFunctions.data__frontend_data_log_enabled == 1 -) { - sendBotDetectorLogToAltSessions(1000); -} - /** - * Send BotDetector logs data to alternative sessions. - * If log_last_update has changed and log contains new event types, the log will be sent to the alternative sessions. - * @param {int} cronStartTimeout delay before cron start - * @param {int} interval check fires on interval + * Bot detector browser state. + * + * The state is passed to the site backend with the current JS->PHP transport and goes + * to the moderate request as sender_info.bot_detector_frontend_data_log. */ -function sendBotDetectorLogToAltSessions(cronStartTimeout = 3000, interval = 1000) { - setTimeout(function() { - setInterval(function() { - const currentLog = apbctLocalStorage.get('ct_bot_detector_frontend_data_log'); - if (needsSaveLogToAltSessions(currentLog)) { - botDetectorLogLastUpdate = currentLog.log_last_update; - // the log will be taken from javascriptclientdata - ctSetAlternativeCookie([], {forceAltCookies: true}); - } - }, interval); - }, cronStartTimeout); -} +class ApbctBrowserState { + static STATE_KEY = 'apbct_browser_state'; + static LOG_KEY = 'ct_bot_detector_frontend_data_log'; + static SCRIPT_SIGNS = { + botd_wrapper_loaded: 'ct-bot-detector-wrapper', + botd_logic_loaded: 'ct-bot-detector.min', + }; + /** + * This LS key is set on bot-detector side + * @type {string} + */ + static TRANSPORT_ENABLED_SIGN_KEY = 'bot_detector_log_transport_enabled'; + static botdWrapperLoaded = 0; + static botdLogicLoaded = 0; -/** - * Check if the log needs to be saved to the alt sessions. If the log has new event types, it will be saved. - * @param {object} currentLog - * @return {boolean} - */ -function needsSaveLogToAltSessions(currentLog) { - if ( - currentLog && currentLog.hasOwnProperty('log_last_update') && - botDetectorLogLastUpdate !== currentLog.log_last_update - ) { - try { - for (let i = 0; i < currentLog.records.length; i++) { - const currentType = currentLog.records[i].frontend_data.js_event; - // check if this event type was already collected - if (currentType !== undefined && botDetectorLogEventTypesCollected.includes(currentType)) { - continue; + /** + * Get the current browser state as a JSON string ready to be transferred. + * @return {string} Empty string if the bot detector is disabled or on any collecting error. + */ + static getFrontendDataLog() { + const prefix = (typeof ctPublicFunctions !== 'undefined' && ctPublicFunctions.cookiePrefix) ? + ctPublicFunctions.cookiePrefix : + ''; + const logKey = prefix + ApbctBrowserState.LOG_KEY; + const noPrefixLogKey = ApbctBrowserState.LOG_KEY; + + if (typeof apbctLocalStorage !== 'undefined' && apbctLocalStorage.get) { + const logObject = apbctLocalStorage.get(logKey) || apbctLocalStorage.get(noPrefixLogKey) || null; + if (logObject && typeof logObject === 'string') { + try { + return JSON.parse(logObject); + } catch (e) { + return ''; } - // add new event type to collection, this type will be sent to the alt sessions further - botDetectorLogEventTypesCollected.push(currentType); - return true; } + return logObject; + } + + let rawLog = localStorage.getItem(logKey); + if (!rawLog) { + rawLog = localStorage.getItem(noPrefixLogKey) || null; + } + + try { + return typeof rawLog === 'string' ? JSON.parse(rawLog) : rawLog; } catch (e) { - console.log('APBCT: bot detector log collection error: ' . e.toString()); + return ''; } } - return false; -} + /** + * + * @return {object} + */ + static asDTO() { + return { + botd_logic_loaded: ApbctBrowserState.botdLogicLoaded, + botd_wrapper_loaded: ApbctBrowserState.botdWrapperLoaded, + frontend_data_log: '', + transport_enabled: 1, + }; + } + + /** + * Look for the bot detector scripts in the page DOM. + * @return {boolean} True if both scripts are found. + */ + static detectScripts() { + if (ApbctBrowserState.botdWrapperLoaded && ApbctBrowserState.botdLogicLoaded) { + return true; + } + + const scripts = document.getElementsByTagName('script'); + + for (let i = 0; i < scripts.length; i++) { + const src = scripts[i].getAttribute('src'); + if (!src) { + continue; + } + if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_wrapper_loaded) !== -1) { + ApbctBrowserState.botdWrapperLoaded = 1; + } else if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_logic_loaded) !== -1) { + ApbctBrowserState.botdLogicLoaded = 1; + } + } + + // The bot detector logic sets this flag on its own start + return !!ApbctBrowserState.botdWrapperLoaded && !!ApbctBrowserState.botdLogicLoaded; + } +} +/** + * Get the browser state as a key/value pair to attach it to an intercepted request. + * @return {{key: string, value: string}|false} False if there is nothing to attach. + */ +function apbctGetBrowserStatePair() { // eslint-disable-line no-unused-vars + try { + ApbctBrowserState.detectScripts(); + let state = ApbctBrowserState.asDTO(); + if ( ApbctBrowserState.botdLogicLoaded ) { + const transportEnabled = localStorage.getItem(ApbctBrowserState.TRANSPORT_ENABLED_SIGN_KEY) === '1'; + if (transportEnabled) { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } else { + state.transport_enabled = 0; + } + } else { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } + return {key: ApbctBrowserState.STATE_KEY, value: JSON.stringify(state)}; + } catch (e) { + return false; + } +} let ctCheckedEmails = {}; let ctCheckedEmailsExist = {}; diff --git a/js/prebuild/apbct-public-bundle_ext-protection.js b/js/prebuild/apbct-public-bundle_ext-protection.js index 176785df6..8518e1712 100644 --- a/js/prebuild/apbct-public-bundle_ext-protection.js +++ b/js/prebuild/apbct-public-bundle_ext-protection.js @@ -2253,7 +2253,7 @@ function ctSetCookie( cookies, value, expires='') { let listOfCookieNamesToForceAlt = [ 'ct_sfw_pass_key', 'ct_sfw_passed', - 'wordpress_apbct_antibot', + 'apbct_antibot', 'apbct_anticrawler_passed', 'apbct_bot_detector_exist', 'apbct_antiflood_passed', @@ -2642,6 +2642,15 @@ function getNoCookieData() { // eslint-disable-line no-unused-vars let noCookieDataLocal = apbctLocalStorage.getCleanTalkData(); let noCookieDataSession = apbctSessionStorage.getCleanTalkData(); let noCookieData = {...noCookieDataLocal, ...noCookieDataSession}; + + // Bot detector browser state is transferred with the hidden field on the NoCookie mode + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + noCookieData[browserState.key] = browserState.value; + } + } + noCookieData = JSON.stringify(noCookieData); return '_ct_no_cookie_data_' + btoa(unescape(encodeURIComponent(noCookieData))); @@ -2669,7 +2678,21 @@ function getCleanTalkStorageDataArray() { // eslint-disable-line no-unused-vars noCookieDataFromUserActivity = {collecting_user_activity_data: collectingUserActivityData}; } - return {...noCookieDataLocal, ...noCookieDataSession, ...noCookieDataTypo, ...noCookieDataFromUserActivity}; + let browserStateData = {}; + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + browserStateData[browserState.key] = browserState.value; + } + } + + return { + ...noCookieDataLocal, + ...noCookieDataSession, + ...noCookieDataTypo, + ...noCookieDataFromUserActivity, + ...browserStateData, + }; } /** @@ -3314,6 +3337,9 @@ class ApbctHandler { const eventTokenKey = useUnwrappedCleantalkKeys ? 'ct_bot_detector_event_token' : 'data%5Bct_bot_detector_event_token%5D'; + const browserStateKey = useUnwrappedCleantalkKeys ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; if (!( +ctPublic.bot_detector_enabled && @@ -3338,6 +3364,12 @@ class ApbctHandler { } } + const browserState = apbctGetBrowserStatePair(); + if (browserState && body.indexOf('apbct_browser_state') === -1) { + addidionalCleantalkData += '&' + browserStateKey + '=' + + encodeURIComponent(browserState.value); + } + body += addidionalCleantalkData; } @@ -3354,6 +3386,11 @@ class ApbctHandler { body.append('ct_bot_detector_event_token', eventToken); } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState && !body.has(browserState.key)) { + body.append(browserState.key, browserState.value); + } } if (isNeedToAddCleantalkDataCheckJsonData) { @@ -3391,6 +3428,22 @@ class ApbctHandler { } } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + try { + const bodyObj = JSON.parse(body); + if ( + bodyObj && typeof bodyObj === 'object' && + !Object.prototype.hasOwnProperty.call(bodyObj, browserState.key) + ) { + bodyObj[browserState.key] = browserState.value; + body = JSON.stringify(bodyObj); + } + } catch (e) { + // body is not JSON — leave as is + } + } } return originalSend.apply(this, [body]); @@ -3448,6 +3501,11 @@ class ApbctHandler { } else { args[1].body.append('ct_no_cookie_hidden_field', getNoCookieData()); } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + args[1].body.append(browserState.key, browserState.value); + } } } } catch (e) { @@ -3504,6 +3562,22 @@ class ApbctHandler { * @return {string|FormData} Modified body. */ const attachFieldsToBody = function(body, fieldPair = false) { + const fieldPairs = [fieldPair, apbctGetBrowserStatePair()]; + + for (const pair of fieldPairs) { + body = attachFieldPairToBody(body, pair); + } + + return body; + }; + + /** + * Attach a single key/value pair to fetch request body + * @param {string|FormData} body Fetch request data body. + * @param {object|bool} fieldPair Key value to inject. + * @return {string|FormData} Modified body. + */ + const attachFieldPairToBody = function(body, fieldPair = false) { if (fieldPair) { if (body instanceof FormData || typeof body.append === 'function') { body.append(fieldPair.key, fieldPair.value); @@ -3761,255 +3835,1041 @@ class ApbctHandler { // Continue even if error } } - - // === WooCommerce add to cart (direct add-item URL) === - if ( - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/cart/add-item') - ) { - try { - if (+ctPublic.settings__forms__wc_add_to_cart) { - args[1].body = attachFieldsToBody( - args[1].body, - selectFieldsData(+ctPublic.bot_detector_enabled), - ); - } - } catch (e) { - // Continue even if error + + // === WooCommerce add to cart (direct add-item URL) === + if ( + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/cart/add-item') + ) { + try { + if (+ctPublic.settings__forms__wc_add_to_cart) { + args[1].body = attachFieldsToBody( + args[1].body, + selectFieldsData(+ctPublic.bot_detector_enabled), + ); + } + } catch (e) { + // Continue even if error + } + } + + // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === + if ( + +ctPublic.settings__forms__wc_add_to_cart && + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/batch') && + typeof args[1].body === 'string' + ) { + try { + const batchPayload = JSON.parse(args[1].body); + if (batchPayload.requests && Array.isArray(batchPayload.requests)) { + const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); + const browserState = apbctGetBrowserStatePair(); + for (const req of batchPayload.requests) { + const isAddItem = req.path === '/wc/store/v1/cart/add-item'; + if (isAddItem && req.body && fieldPair && fieldPair.key) { + req.body[fieldPair.key] = fieldPair.value; + } + if (isAddItem && req.body && browserState) { + req.body[browserState.key] = browserState.value; + } + } + args[1].body = JSON.stringify(batchPayload); + } + } catch (e) { + // Continue even if error + } + } + + // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === + preventOriginalFetch = await processIframeCommonFetch(url, args); + + // Return original fetch result if not prevented + if (!preventOriginalFetch) { + return originalFetch.apply(this, args); + } + } catch (error) { + // In case of any error in our interceptor, call original fetch + return originalFetch.apply(this, args); + } + }; + } + + /** + * Prepare jQuery.ajaxPrefilter to add CleanTalk data to jQuery ajax requests. + * Notes: + * - ajaxSetup.beforeSend is not used: a request can supply its own beforeSend and drop the default. + * - ajaxPrefilter runs for every jQuery ajax call after options are merged, so injection is guaranteed. + * - Form signs are checked on the request data/url at send time. + * - Any sign of the form HTML of the caller is insignificant in this process. + * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script + * will work independing if jQuery is loaded by CleanTalk or not + * @return {void} + */ + catchJqueryAjax() { + if ( typeof jQuery !== 'undefined' && typeof jQuery.ajaxPrefilter === 'function' ) { + jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { + const handler = new ApbctHandler(); + const sourceSign = handler.searchSignsForJQAjaxInjection(options, originalOptions); + if (sourceSign.found !== false) { + options.data = handler.injectCleantalkDataToJQAjax( + sourceSign, + handler.getJQAjaxPayloadForInject(options, originalOptions), + options, + ); + } + }); + } + } + + /** + * jQuery.param() on URLSearchParams/FormData can collapse options.data to "". + * Sign search already falls back to originalOptions; inject must use that payload too. + * @param {object} options + * @param {object=} originalOptions + * @return {*} + */ + getJQAjaxPayloadForInject(options, originalOptions) { + const current = options && options.data; + const original = originalOptions && originalOptions.data; + if ( this.jqAjaxPayloadWasCollapsed(current, original) ) { + return original; + } + return current; + } + + /** + * @param {*} current + * @param {*} original + * @return {boolean} + */ + jqAjaxPayloadWasCollapsed(current, original) { + if ( original === null || typeof original === 'undefined' ) { + return false; + } + if ( current === original ) { + return false; + } + const currentEmpty = current === '' || current === null || typeof current === 'undefined'; + if ( !currentEmpty ) { + return false; + } + if ( typeof original === 'string' ) { + return original !== ''; + } + return this.isJQAjaxFormData(original) || + this.isJQAjaxURLSearchParams(original) || + this.isJQAjaxPlainObjectOrArray(original); + } + + /** + * Normalize jQuery ajax data to a query string for sign search. + * Objects and serializeArray are read structurally so search never calls jQuery.param. + * Also reads known sign fields from the URL (IE11 FormData cannot be enumerated). + * @param {object} ajaxObject Ajax options object. + * @return {string} + */ + getJQAjaxDataAsString(ajaxObject) { + if ( !ajaxObject || typeof ajaxObject !== 'object' ) { + return ''; + } + let fromData = ''; + if ( typeof ajaxObject.data === 'string' ) { + fromData = ajaxObject.data; + } else if ( this.isJQAjaxPlainObjectOrArray(ajaxObject.data) ) { + fromData = this.getStructuredJQAjaxSignString(ajaxObject.data); + } else if ( this.isJQAjaxURLSearchParams(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } else if ( this.isJQAjaxFormData(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } + // Native IE11 FormData is write-only (no get/forEach/entries). Signs then come from the URL. + const fromUrl = this.collectKnownSignStringFromUrl(ajaxObject.url); + if ( fromData && fromUrl ) { + return fromData + '&' + fromUrl; + } + return fromData || fromUrl; + } + + /** + * Build a sign string from top-level fields without serializing the whole payload. + * @param {object|Array} data + * @return {string} + */ + getStructuredJQAjaxSignString(data) { + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return this.getSerializeArraySignString(data); + } + const parts = []; + const action = this.getPlainObjectSignField(data, 'action'); + if ( typeof action === 'string' && action !== '' ) { + parts.push('action=' + action); + } + const nonce = this.getPlainObjectSignField(data, 'ur_frontend_form_nonce'); + if ( nonce !== null ) { + parts.push('ur_frontend_form_nonce=' + nonce); + } + if ( this.plainObjectHasTwtCcSignup(data) ) { + parts.push('twt_cc_signup=1'); + } + return parts.join('&'); + } + + /** + * Read action/nonce from top-level, data[key], or nested data.key. + * @param {object} data + * @param {string} key + * @return {string|number|null} + */ + getPlainObjectSignField(data, key) { + if ( !data || typeof data !== 'object' ) { + return null; + } + if ( this.isJQAjaxScalarSignValue(data[key]) ) { + return data[key]; + } + const bracketKey = 'data[' + key + ']'; + if ( this.isJQAjaxScalarSignValue(data[bracketKey]) ) { + return data[bracketKey]; + } + if ( + data.data && + typeof data.data === 'object' && + Object.prototype.toString.call(data.data) !== '[object Array]' && + this.isJQAjaxScalarSignValue(data.data[key]) + ) { + return data.data[key]; + } + return null; + } + + /** + * @param {*} value + * @return {boolean} + */ + isJQAjaxScalarSignValue(value) { + return typeof value === 'string' || typeof value === 'number'; + } + + /** + * @param {object} data + * @param {number=} depth + * @return {boolean} + */ + plainObjectHasTwtCcSignup(data, depth) { + if ( !data || typeof data !== 'object' ) { + return false; + } + if ( typeof depth === 'undefined' ) { + depth = 0; + } + if ( depth > 2 ) { + return false; + } + for ( const key in data ) { + if ( !Object.prototype.hasOwnProperty.call(data, key) ) { + continue; + } + const normalizedKey = this.unwrapJQAjaxFormDataKey(key); + if ( normalizedKey === 'twt_cc_signup' || key.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + const value = data[key]; + if ( typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + if ( + value && + typeof value === 'object' && + Object.prototype.toString.call(value) !== '[object Array]' + ) { + if ( this.plainObjectHasTwtCcSignup(value, depth + 1) ) { + return true; + } + } + } + return false; + } + + /** + * @param {Array} entries + * @return {string} + */ + getSerializeArraySignString(entries) { + const parts = []; + for ( let i = 0; i < entries.length; i++ ) { + const entry = entries[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + continue; + } + const value = entry.value; + const normalizedKey = this.unwrapJQAjaxFormDataKey(entry.name); + if ( this.isJQAjaxKnownSignField(normalizedKey, value) ) { + parts.push(normalizedKey + '=' + value); + } + } + return parts.join('&'); + } + + /** + * True for serializeArray payloads, including an empty array. + * @param {Array} data + * @return {boolean} + */ + isJQAjaxSerializeArray(data) { + if ( Object.prototype.toString.call(data) !== '[object Array]' ) { + return false; + } + for ( let i = 0; i < data.length; i++ ) { + const entry = data[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + return false; + } + } + return true; + } + + /** + * Cross-realm URLSearchParams (instanceof fails across windows). + * @param {*} data + * @return {boolean} + */ + isJQAjaxURLSearchParams(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object URLSearchParams]' ) { + return true; + } + if ( tag === '[object FormData]' ) { + return false; + } + return typeof data.sort === 'function' && typeof data.get === 'function'; + } + + /** + * Cross-realm FormData, including common polyfills. + * @param {*} data + * @return {boolean} + */ + isJQAjaxFormData(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) || this.isJQAjaxURLSearchParams(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object FormData]' ) { + return true; + } + if ( tag === '[object Headers]' || typeof data.getSetCookie === 'function' ) { + return false; + } + return typeof data.forEach === 'function' || + typeof data.get === 'function' || + typeof data.entries === 'function'; + } + + /** + * Collect only known sign fields from FormData / URLSearchParams. + * Unwrap data[action] so later action=... checks match. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + collectKnownSignStringFromKeyValueBag(bag) { + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' ) { + return; + } + const valueAsString = String(value); + const normalizedKey = unwrapKey(key); + if ( + knownKeys[normalizedKey] || + valueAsString.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + valueAsString); + } + }); + if ( collected ) { + return parts.join('&'); + } + if ( typeof bag.get !== 'function' ) { + return ''; + } + const keysToProbe = [ + 'action', + 'ur_frontend_form_nonce', + 'twt_cc_signup', + ]; + const getParts = []; + for ( let i = 0; i < keysToProbe.length; i++ ) { + const key = keysToProbe[i]; + const value = this.getFormDataScalarValue(bag, [key, 'data[' + key + ']']); + if ( value !== null ) { + getParts.push(key + '=' + value); + } + } + return getParts.join('&'); + } + + /** + * Known sign fields from a request URL query. IE11-safe (no URLSearchParams). + * @param {string} url + * @return {string} + */ + collectKnownSignStringFromUrl(url) { + if ( typeof url !== 'string' || url === '' ) { + return ''; + } + const queryIndex = url.indexOf('?'); + if ( queryIndex === -1 || queryIndex === url.length - 1 ) { + return ''; + } + const hashIndex = url.indexOf('#', queryIndex); + const query = hashIndex === -1 ? + url.slice(queryIndex + 1) : + url.slice(queryIndex + 1, hashIndex); + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const pairs = query.split('&'); + for ( let i = 0; i < pairs.length; i++ ) { + const pair = pairs[i]; + if ( !pair ) { + continue; + } + const eq = pair.indexOf('='); + let rawKey = eq === -1 ? pair : pair.slice(0, eq); + let rawValue = eq === -1 ? '' : pair.slice(eq + 1); + try { + rawKey = decodeURIComponent(rawKey.replace(/\+/g, ' ')); + rawValue = decodeURIComponent(rawValue.replace(/\+/g, ' ')); + } catch (e) { + continue; + } + const normalizedKey = unwrapKey(rawKey); + if ( + knownKeys[normalizedKey] || + rawValue.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + rawValue); + } + } + return parts.join('&'); + } + + /** + * Walk FormData/URLSearchParams via forEach, then entries() for polyfills that only have an iterator. + * @param {FormData|URLSearchParams} bag + * @param {Function} callback + * @return {boolean} + */ + forEachJQAjaxKeyValueBag(bag, callback) { + if ( typeof bag.forEach === 'function' ) { + try { + bag.forEach(callback); + return true; + } catch (e) { + // Fall through to entries(). + } + } + if ( typeof bag.entries !== 'function' ) { + return false; + } + try { + const iterator = bag.entries(); + if ( !iterator || typeof iterator.next !== 'function' ) { + return false; + } + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + callback(pair[1], pair[0]); + } + step = iterator.next(); + } + return true; + } catch (e) { + return false; + } + } + + /** + * @return {Object} + */ + getJQAjaxKnownSignKeys() { + const knownKeys = Object.create(null); + knownKeys.action = true; + knownKeys.ur_frontend_form_nonce = true; + knownKeys.twt_cc_signup = true; + return knownKeys; + } + + /** + * @param {string} normalizedKey + * @param {*} value + * @return {boolean} + */ + isJQAjaxKnownSignField(normalizedKey, value) { + if ( + normalizedKey === 'action' || + normalizedKey === 'ur_frontend_form_nonce' || + normalizedKey === 'twt_cc_signup' || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + return true; + } + return typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1; + } + + /** + * Treat data[action] as action for WP-style payloads. + * @param {string} key + * @return {string} + */ + unwrapJQAjaxFormDataKey(key) { + if ( typeof key !== 'string' ) { + return ''; + } + if ( key.length > 6 && key.indexOf('data[') === 0 && key.charAt(key.length - 1) === ']' ) { + return key.slice(5, -1); + } + return key; + } + + /** + * @param {FormData} formData + * @param {Array.} keys + * @return {string|number|null} + */ + getFormDataScalarValue(formData, keys) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && (typeof value === 'string' || typeof value === 'number') ) { + return value; + } + } + return null; + } + + /** + * True for arrays and plain objects that jQuery.param can serialize safely. + * @param {*} data + * @return {boolean} + */ + isJQAjaxPlainObjectOrArray(data) { + if ( data === null || typeof data !== 'object' ) { + return false; + } + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return true; + } + if ( typeof jQuery !== 'undefined' && typeof jQuery.isPlainObject === 'function' ) { + return jQuery.isPlainObject(data); + } + const proto = Object.getPrototypeOf(data); + return proto === Object.prototype || proto === null; + } + + /** + * Search for sign within AJAX data to do inject CleanTalk data. + * @param {object} ajaxObject Ajax object. + * @param {object=} originalOptions Original jQuery ajax options before merge. + * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + */ + searchSignsForJQAjaxInjection(ajaxObject, originalOptions) { + let sourceSign = { + 'found': false, + 'keepUnwrapped': false, + 'attachVisibleFieldsData': false, + }; + let dataString = this.getJQAjaxDataAsString(ajaxObject); + if ( !dataString && originalOptions && originalOptions !== ajaxObject ) { + dataString = this.getJQAjaxDataAsString(originalOptions); + } + + if ( dataString.indexOf('action=fl_builder_subscribe_form_submit') !== -1 ) { + sourceSign.found = 'fl_builder_subscribe_form_submit'; + } + if ( dataString.indexOf('twt_cc_signup') !== -1 ) { + sourceSign.found = 'twt_cc_signup'; + } + if ( dataString.indexOf('action=mailpoet') !== -1 ) { + sourceSign.found = 'action=mailpoet'; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=user_registration') !== -1 && + dataString.indexOf('ur_frontend_form_nonce') !== -1 + ) { + sourceSign.found = 'action=user_registration'; + } + if ( dataString.indexOf('action=happyforms_message') !== -1 ) { + sourceSign.found = 'action=happyforms_message'; + } + if ( dataString.indexOf('action=new_activity_comment') !== -1 ) { + sourceSign.found = 'action=new_activity_comment'; + } + if ( dataString.indexOf('action=wwlc_create_user') !== -1 ) { + sourceSign.found = 'action=wwlc_create_user'; + } + if ( dataString.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 ) { + sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=drplus_signup') !== -1 ) { + sourceSign.found = 'action=drplus_signup'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=bt_cc') !== -1 ) { + sourceSign.found = 'action=bt_cc'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=wpr_form_builder_email') !== -1 ) { + sourceSign.found = 'action=wpr_form_builder_email'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=nf_ajax_submit') !== -1 ) { + sourceSign.found = 'action=nf_ajax_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=uael_register_user') !== -1 && + ctPublic.data__cookies_type === 'none' + ) { + sourceSign.found = 'action=uael_register_user'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=SQBSubmitQuizAjax') !== -1 ) { + sourceSign.found = 'action=SQBSubmitQuizAjax'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=user_registration_user_form_submit') !== -1 ) { + sourceSign.found = 'action=user_registration_user_form_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=bloom_subscribe') !== -1 ) { + sourceSign.found = 'action=bloom_subscribe'; + sourceSign.keepUnwrapped = true; + } + if ( + this.isJQAjaxFormData(ajaxObject.data) && + typeof ajaxObject.data.get === 'function' && + ajaxObject.data.get('action') === 'pafe_ajax_form_builder' + ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } else if ( dataString.indexOf('action=pafe_ajax_form_builder') !== -1 ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } + + // woocommerce add to cart is based on URL + if ( typeof ajaxObject.url === 'string' && ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1 ) { + sourceSign.found = 'wc-ajax=add_to_cart'; + // GET/HEAD: PHP reads Get::get('ct_bot_detector_event_token'), not data[...]. + if ( this.isJQAjaxNoContentMethod(ajaxObject) ) { + sourceSign.keepUnwrapped = true; + } + } + + return sourceSign; + } + + /** + * Inject CleanTalk data into jQuery ajax payload of any supported type. + * @param {object} sourceSign + * @param {*} ajaxData + * @param {object=} ajaxOptions jQuery ajax options (traditional, processData, contentType). + * Keep URLSearchParams/objects when processData or contentType is false. + * URLSearchParams must also disable processData, or jQuery.param() later yields "". + * GET/HEAD never keep the original type: jQuery only puts string data on the URL. + * @return {*} + */ + injectCleantalkDataToJQAjax(sourceSign, ajaxData, ajaxOptions) { + const traditional = ajaxOptions && ajaxOptions.traditional; + const keepOriginalType = !this.isJQAjaxNoContentMethod(ajaxOptions) && !!(ajaxOptions && ( + ajaxOptions.processData === false || + ajaxOptions.contentType === false + )); + + if ( ajaxData === null || typeof ajaxData === 'undefined' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ''); + } + if ( typeof ajaxData === 'string' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData); + } + if ( this.isJQAjaxPlainObjectOrArray(ajaxData) ) { + if ( keepOriginalType ) { + if ( Object.prototype.toString.call(ajaxData) === '[object Array]' ) { + if ( this.isJQAjaxSerializeArray(ajaxData) ) { + return this.injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData); + } + return ajaxData; + } + return this.injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData); + } + try { + if ( typeof jQuery !== 'undefined' && typeof jQuery.param === 'function' ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + jQuery.param(ajaxData, traditional), + ); + } + } catch (e) { + return ajaxData; + } + return ajaxData; + } + if ( this.isJQAjaxURLSearchParams(ajaxData) ) { + if ( keepOriginalType ) { + this.preserveJQAjaxURLSearchParamsOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxKeyValue( + sourceSign, + this.cloneURLSearchParams(ajaxData), + ); + } + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData.toString()); + } + if ( this.isJQAjaxFormData(ajaxData) ) { + if ( this.isJQAjaxNoContentMethod(ajaxOptions) ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + this.serializeJQAjaxKeyValueBag(ajaxData), + ); + } + this.preserveJQAjaxFormDataOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxFormData( + sourceSign, + this.cloneFormData(ajaxData), + ); + } + return ajaxData; + } + + /** + * GET/HEAD have no body. Missing type is GET (jQuery default). + * @param {object=} ajaxOptions + * @return {boolean} + */ + isJQAjaxNoContentMethod(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return false; + } + const type = ajaxOptions.type || ajaxOptions.method; + if ( typeof type !== 'string' || type === '' ) { + return true; + } + const method = type.toUpperCase(); + return method === 'GET' || method === 'HEAD'; + } + + /** + * Collect CleanTalk fields to append to a key/value payload. + * @param {object} sourceSign + * @return {Array.>} + */ + getCleantalkJQAjaxFieldPairs(sourceSign) { + const pairs = []; + const wrapKey = function(key) { + return sourceSign.keepUnwrapped ? key : 'data[' + key + ']'; + }; + + if ( + +ctPublic.bot_detector_enabled && + apbctLocalStorage.get('bot_detector_event_token') + ) { + const token = this.toolGetEventToken(); + if ( token ) { + pairs.push([wrapKey('ct_bot_detector_event_token'), token]); + } + } else { + const noCookieData = getNoCookieData(); + if ( noCookieData ) { + pairs.push([wrapKey('ct_no_cookie_hidden_field'), noCookieData]); + } + } + + const browserState = apbctGetBrowserStatePair(); + if ( browserState ) { + const browserStateKey = sourceSign.keepUnwrapped ? + browserState.key : + 'data[' + browserState.key + ']'; + pairs.push([browserStateKey, browserState.value]); + } + + return pairs; + } + + /** + * jQuery.param(FormData) after the prefilter yields "". Keep the body as FormData. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxFormDataOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + ajaxOptions.contentType = false; + } + + /** + * jQuery.param(URLSearchParams) after the prefilter yields "". Keep the body as URLSearchParams. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxURLSearchParamsOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + } + + /** + * Read a FormData field via get(), forEach(), or entries(). + * Native IE11 FormData is write-only and cannot be read. + * @param {FormData} formData + * @param {Array.} keys + * @return {*} + */ + getFormDataField(formData, keys) { + if ( typeof formData.get === 'function' ) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && typeof value !== 'undefined' ) { + return value; + } + } + } + if ( typeof formData.forEach === 'function' ) { + let found = null; + formData.forEach(function(value, key) { + if ( found !== null ) { + return; + } + for ( let i = 0; i < keys.length; i++ ) { + if ( key === keys[i] ) { + found = value; + return; } } - - // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === - if ( - +ctPublic.settings__forms__wc_add_to_cart && - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/batch') && - typeof args[1].body === 'string' - ) { - try { - const batchPayload = JSON.parse(args[1].body); - if (batchPayload.requests && Array.isArray(batchPayload.requests)) { - const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); - for (const req of batchPayload.requests) { - const isAddItem = req.path === '/wc/store/v1/cart/add-item'; - if (isAddItem && req.body && fieldPair && fieldPair.key) { - req.body[fieldPair.key] = fieldPair.value; + }); + if ( found !== null ) { + return found; + } + } + if ( typeof formData.entries === 'function' ) { + try { + const iterator = formData.entries(); + if ( iterator && typeof iterator.next === 'function' ) { + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + for ( let i = 0; i < keys.length; i++ ) { + if ( pair[0] === keys[i] ) { + return pair[1]; } } - args[1].body = JSON.stringify(batchPayload); } - } catch (e) { - // Continue even if error + step = iterator.next(); } } - - // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === - preventOriginalFetch = await processIframeCommonFetch(url, args); - - // Return original fetch result if not prevented - if (!preventOriginalFetch) { - return originalFetch.apply(this, args); - } - } catch (error) { - // In case of any error in our interceptor, call original fetch - return originalFetch.apply(this, args); + } catch (e) { + return null; } - }; + } + return null; } /** - * Prepare jQuery.ajaxSetup to add nocookie data to the jQuery ajax request. - * Notes: - * - Do it just once, the ajaxSetup.beforeSend will be overwritten for any calls. - * - Signs of forms need to be caught will be checked during ajaxSetup.settings.data process on send. - * - Any sign of the form HTML of the caller is insignificant in this process. - * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script - * will work independing if jQuery is loaded by CleanTalk or not - * @return {void} + * Clone URLSearchParams so the caller's instance is not mutated. + * @param {URLSearchParams} params + * @return {URLSearchParams} */ - catchJqueryAjax() { - if ( typeof jQuery !== 'undefined') { - // this code run on base ajax rules - so do not work due scripts use it's own ajax object injections - if ( typeof jQuery.ajaxSetup === 'function' ) { - jQuery.ajaxSetup({ - beforeSend: function(xhr, settings) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(settings, 'ajaxSetup'); - if (sourceSign.found !== false) { - settings.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, settings.data); - } - }, - }); + cloneURLSearchParams(params) { + const serialized = typeof params.toString === 'function' ? params.toString() : ''; + if ( typeof params.constructor === 'function' && params.constructor !== Object ) { + try { + return new params.constructor(serialized); + } catch (e) { + // Fall through to the current-window constructor. } - // this code run on ANY ajax on ANY script queue status - // todo Probably move all ajaxSetup actions to ajaxPrefilter - if ( typeof jQuery.ajaxPrefilter === 'function' ) { - jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(options, 'ajaxPrefilter'); - if (sourceSign.found !== false) { - if (typeof options.data === 'string') { - options.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, options.data); - } - if ( - typeof options.data === 'object' && - typeof options.data.append === 'function' - ) { - options.data = handler.injectCleantalkDataToJQAjaxFormData(sourceSign, options.data); - } - } - }); + } + if ( typeof URLSearchParams === 'function' ) { + try { + return new URLSearchParams(serialized); + } catch (e) { + return params; } } + return params; } /** - * Search for sign within AJAX data to do inject CleanTalk data. - * @param {object} ajaxObject Ajax object. - * @param {string} catchOn Function should be catched on. - * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + * Clone FormData when it can be enumerated (forEach or entries); otherwise reuse. + * @param {FormData} formData + * @return {FormData} */ - searchSignsForJQAjaxInjection(ajaxObject, catchOn = 'ajaxSetup') { - let sourceSign = { - 'found': false, - 'keepUnwrapped': false, - 'attachVisibleFieldsData': false, - }; - // on ajaxSetup - if (catchOn === 'ajaxSetup') { - // settings data is string (important!) - if ( typeof ajaxObject.data === 'string' ) { - if ( - ajaxObject.data.indexOf('action=fl_builder_subscribe_form_submit') !== -1 - ) { - sourceSign.found = 'fl_builder_subscribe_form_submit'; - } - if ( - ajaxObject.data.indexOf('twt_cc_signup') !== -1 - ) { - sourceSign.found = 'twt_cc_signup'; - } - if ( - ajaxObject.data.indexOf('action=mailpoet') !== -1 - ) { - sourceSign.found = 'action=mailpoet'; - sourceSign.attachVisibleFieldsData = true; - } - - if ( - ajaxObject.data.indexOf('action=user_registration') !== -1 && - ajaxObject.data.indexOf('ur_frontend_form_nonce') !== -1 - ) { - sourceSign.found = 'action=user_registration'; - } - - if (ajaxObject.data.indexOf('action=happyforms_message') !== -1) { - sourceSign.found = 'action=happyforms_message'; - } + cloneFormData(formData) { + try { + const clone = new FormData(); + const copied = this.forEachJQAjaxKeyValueBag(formData, function(value, key) { + clone.append(key, value); + }); + if ( copied ) { + return clone; + } + } catch (e) { + return formData; + } + return formData; + } - if ( - ajaxObject.data.indexOf('action=new_activity_comment') !== -1 - ) { - sourceSign.found = 'action=new_activity_comment'; - } - if ( - ajaxObject.data.indexOf('action=wwlc_create_user') !== -1 - ) { - sourceSign.found = 'action=wwlc_create_user'; - } - if ( - ajaxObject.data.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 - ) { - sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=drplus_signup') !== -1 - ) { - sourceSign.found = 'action=drplus_signup'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=bt_cc') !== -1 - ) { - sourceSign.found = 'action=bt_cc'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=wpr_form_builder_email') !== -1 - ) { - sourceSign.found = 'action=wpr_form_builder_email'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=nf_ajax_submit') !== -1 - ) { - sourceSign.found = 'action=nf_ajax_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=uael_register_user') !== -1 && - ctPublic.data__cookies_type === 'none' - ) { - sourceSign.found = 'action=uael_register_user'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=SQBSubmitQuizAjax') !== -1 - ) { - sourceSign.found = 'action=SQBSubmitQuizAjax'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=user_registration_user_form_submit') !== -1 - ) { - sourceSign.found = 'action=user_registration_user_form_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } + /** + * Form-urlencoded string from FormData/URLSearchParams. Skip File/Blob values. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + serializeJQAjaxKeyValueBag(bag) { + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { + return; } - // wooocommerce add to cart is based on URL - if ( typeof ajaxObject.url === 'string' ) { - if (ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1) { - sourceSign.found = 'wc-ajax=add_to_cart'; + parts.push(encodeURIComponent(String(key)) + '=' + encodeURIComponent(String(value))); + }); + if ( collected ) { + return parts.join('&'); + } + return ''; + } + + /** + * Inject CleanTalk fields into URLSearchParams without changing the payload type. + * @param {object} sourceSign + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + injectCleantalkDataToJQAjaxKeyValue(sourceSign, params) { + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + params.append(pairs[i][0], pairs[i][1]); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( extractor ) { + const extracted = extractor.extract(params.toString()); + if ( typeof extracted === 'string' ) { + params.append('apbct_visible_fields', extracted); } } } + return params; + } - // on ajaxPrefilter - if (catchOn === 'ajaxPrefilter') { - if (typeof ajaxObject.data === 'string') { - if (ajaxObject.data.indexOf('action=bloom_subscribe') !== -1) { - sourceSign.found = 'action=bloom_subscribe'; - sourceSign.keepUnwrapped = true; + /** + * Inject CleanTalk fields into a jQuery serializeArray payload. + * @param {object} sourceSign + * @param {Array} ajaxData + * @return {Array} + */ + injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData) { + const result = ajaxData.slice(); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result.push({ + name: pairs[i][0], + value: pairs[i][1], + }); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' + ) { + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.push({ + name: 'apbct_visible_fields', + value: extracted, + }); } } + } + return result; + } + /** + * Inject CleanTalk fields into a plain object without changing the payload type. + * @param {object} sourceSign + * @param {object} ajaxData + * @return {object} + */ + injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData) { + const result = typeof jQuery !== 'undefined' && typeof jQuery.extend === 'function' ? + jQuery.extend({}, ajaxData) : + this.clonePlainObject(ajaxData); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result[pairs[i][0]] = pairs[i][1]; + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); if ( - typeof ajaxObject.data === 'object' && - ajaxObject.data !== null && - typeof ajaxObject.data.get === 'function' + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' ) { - if (ajaxObject.data.get('action') === 'pafe_ajax_form_builder') { - sourceSign.found = 'action=pafe_ajax_form_builder'; - sourceSign.keepUnwrapped = true; + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.apbct_visible_fields = extracted; } } } + return result; + } - return sourceSign; + /** + * IE11-safe shallow copy of a plain object. + * @param {object} ajaxData + * @return {object} + */ + clonePlainObject(ajaxData) { + const result = {}; + for ( const key in ajaxData ) { + if ( Object.prototype.hasOwnProperty.call(ajaxData, key) ) { + result[key] = ajaxData[key]; + } + } + return result; } /** @@ -4021,8 +4881,7 @@ class ApbctHandler { injectCleantalkDataToJQAjaxFormData(sourceSign, ajaxDataFormData) { if ( typeof sourceSign !== 'object' || - typeof ajaxDataFormData !== 'object' || - !(ajaxDataFormData instanceof FormData) + !this.isJQAjaxFormData(ajaxDataFormData) ) { return ajaxDataFormData; } @@ -4053,6 +4912,16 @@ class ApbctHandler { } } + // Bot detector browser state + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append(browserState.key, browserState.value); + } else { + ajaxDataFormData.append('data[' + browserState.key + ']', browserState.value); + } + } + // Visible fields if (sourceSign.attachVisibleFieldsData) { let visibleFieldsSearchResult = false; @@ -4060,13 +4929,10 @@ class ApbctHandler { if (extractor) { // Try to find form_id in FormData to find form container and // collect visible fields only inside it - let formId = null; - for (let pair of ajaxDataFormData.entries()) { - if (pair[0] === 'form_id' || pair[0] === 'data[form_id]') { - formId = pair[1]; - break; - } - } + const formId = this.getFormDataField( + ajaxDataFormData, + ['form_id', 'data[form_id]'], + ); let container = null; if (formId && typeof formId === 'string') { // Sanitize formId to prevent selector injection @@ -4111,6 +4977,15 @@ class ApbctHandler { let eventToken = ''; let noCookieData = ''; let visibleFieldsString = ''; + let browserStateString = ''; + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + const browserStateKey = sourceSign.keepUnwrapped ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; + browserStateString = browserStateKey + '=' + encodeURIComponent(browserState.value) + '&'; + } if ( +ctPublic.bot_detector_enabled && @@ -4127,9 +5002,9 @@ class ApbctHandler { } else { noCookieData = getNoCookieData(); if (sourceSign.keepUnwrapped) { - noCookieData = 'ct_no_cookie_hidden_field=' + noCookieData + '&'; + noCookieData = 'ct_no_cookie_hidden_field=' + encodeURIComponent(noCookieData) + '&'; } else { - noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + noCookieData + '&'; + noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + encodeURIComponent(noCookieData) + '&'; } } @@ -4152,7 +5027,7 @@ class ApbctHandler { } } - return noCookieData + eventToken + visibleFieldsString + ajaxDataString; + return noCookieData + eventToken + browserStateString + visibleFieldsString + ajaxDataString; } /** @@ -6229,67 +7104,126 @@ function apbctIsFormInDiv(formObj, divClassName) { return false; } -let botDetectorLogLastUpdate = 0; -let botDetectorLogEventTypesCollected = []; - -// bot_detector frontend_data log alt session saving cron -if ( - ctPublicFunctions.hasOwnProperty('bot_detector_enabled') && - +ctPublicFunctions.bot_detector_enabled && - ctPublicFunctions.hasOwnProperty('data__frontend_data_log_enabled') && - ctPublicFunctions.data__frontend_data_log_enabled == 1 -) { - sendBotDetectorLogToAltSessions(1000); -} - /** - * Send BotDetector logs data to alternative sessions. - * If log_last_update has changed and log contains new event types, the log will be sent to the alternative sessions. - * @param {int} cronStartTimeout delay before cron start - * @param {int} interval check fires on interval + * Bot detector browser state. + * + * The state is passed to the site backend with the current JS->PHP transport and goes + * to the moderate request as sender_info.bot_detector_frontend_data_log. */ -function sendBotDetectorLogToAltSessions(cronStartTimeout = 3000, interval = 1000) { - setTimeout(function() { - setInterval(function() { - const currentLog = apbctLocalStorage.get('ct_bot_detector_frontend_data_log'); - if (needsSaveLogToAltSessions(currentLog)) { - botDetectorLogLastUpdate = currentLog.log_last_update; - // the log will be taken from javascriptclientdata - ctSetAlternativeCookie([], {forceAltCookies: true}); - } - }, interval); - }, cronStartTimeout); -} +class ApbctBrowserState { + static STATE_KEY = 'apbct_browser_state'; + static LOG_KEY = 'ct_bot_detector_frontend_data_log'; + static SCRIPT_SIGNS = { + botd_wrapper_loaded: 'ct-bot-detector-wrapper', + botd_logic_loaded: 'ct-bot-detector.min', + }; + /** + * This LS key is set on bot-detector side + * @type {string} + */ + static TRANSPORT_ENABLED_SIGN_KEY = 'bot_detector_log_transport_enabled'; + static botdWrapperLoaded = 0; + static botdLogicLoaded = 0; -/** - * Check if the log needs to be saved to the alt sessions. If the log has new event types, it will be saved. - * @param {object} currentLog - * @return {boolean} - */ -function needsSaveLogToAltSessions(currentLog) { - if ( - currentLog && currentLog.hasOwnProperty('log_last_update') && - botDetectorLogLastUpdate !== currentLog.log_last_update - ) { - try { - for (let i = 0; i < currentLog.records.length; i++) { - const currentType = currentLog.records[i].frontend_data.js_event; - // check if this event type was already collected - if (currentType !== undefined && botDetectorLogEventTypesCollected.includes(currentType)) { - continue; + /** + * Get the current browser state as a JSON string ready to be transferred. + * @return {string} Empty string if the bot detector is disabled or on any collecting error. + */ + static getFrontendDataLog() { + const prefix = (typeof ctPublicFunctions !== 'undefined' && ctPublicFunctions.cookiePrefix) ? + ctPublicFunctions.cookiePrefix : + ''; + const logKey = prefix + ApbctBrowserState.LOG_KEY; + const noPrefixLogKey = ApbctBrowserState.LOG_KEY; + + if (typeof apbctLocalStorage !== 'undefined' && apbctLocalStorage.get) { + const logObject = apbctLocalStorage.get(logKey) || apbctLocalStorage.get(noPrefixLogKey) || null; + if (logObject && typeof logObject === 'string') { + try { + return JSON.parse(logObject); + } catch (e) { + return ''; } - // add new event type to collection, this type will be sent to the alt sessions further - botDetectorLogEventTypesCollected.push(currentType); - return true; } + return logObject; + } + + let rawLog = localStorage.getItem(logKey); + if (!rawLog) { + rawLog = localStorage.getItem(noPrefixLogKey) || null; + } + + try { + return typeof rawLog === 'string' ? JSON.parse(rawLog) : rawLog; } catch (e) { - console.log('APBCT: bot detector log collection error: ' . e.toString()); + return ''; } } - return false; -} + /** + * + * @return {object} + */ + static asDTO() { + return { + botd_logic_loaded: ApbctBrowserState.botdLogicLoaded, + botd_wrapper_loaded: ApbctBrowserState.botdWrapperLoaded, + frontend_data_log: '', + transport_enabled: 1, + }; + } + + /** + * Look for the bot detector scripts in the page DOM. + * @return {boolean} True if both scripts are found. + */ + static detectScripts() { + if (ApbctBrowserState.botdWrapperLoaded && ApbctBrowserState.botdLogicLoaded) { + return true; + } + + const scripts = document.getElementsByTagName('script'); + + for (let i = 0; i < scripts.length; i++) { + const src = scripts[i].getAttribute('src'); + if (!src) { + continue; + } + if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_wrapper_loaded) !== -1) { + ApbctBrowserState.botdWrapperLoaded = 1; + } else if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_logic_loaded) !== -1) { + ApbctBrowserState.botdLogicLoaded = 1; + } + } + + // The bot detector logic sets this flag on its own start + return !!ApbctBrowserState.botdWrapperLoaded && !!ApbctBrowserState.botdLogicLoaded; + } +} +/** + * Get the browser state as a key/value pair to attach it to an intercepted request. + * @return {{key: string, value: string}|false} False if there is nothing to attach. + */ +function apbctGetBrowserStatePair() { // eslint-disable-line no-unused-vars + try { + ApbctBrowserState.detectScripts(); + let state = ApbctBrowserState.asDTO(); + if ( ApbctBrowserState.botdLogicLoaded ) { + const transportEnabled = localStorage.getItem(ApbctBrowserState.TRANSPORT_ENABLED_SIGN_KEY) === '1'; + if (transportEnabled) { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } else { + state.transport_enabled = 0; + } + } else { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } + return {key: ApbctBrowserState.STATE_KEY, value: JSON.stringify(state)}; + } catch (e) { + return false; + } +} let ctCheckedEmails = {}; let ctCheckedEmailsExist = {}; diff --git a/js/prebuild/apbct-public-bundle_ext-protection_gathering.js b/js/prebuild/apbct-public-bundle_ext-protection_gathering.js index 4820dfe97..0124e8837 100644 --- a/js/prebuild/apbct-public-bundle_ext-protection_gathering.js +++ b/js/prebuild/apbct-public-bundle_ext-protection_gathering.js @@ -2253,7 +2253,7 @@ function ctSetCookie( cookies, value, expires='') { let listOfCookieNamesToForceAlt = [ 'ct_sfw_pass_key', 'ct_sfw_passed', - 'wordpress_apbct_antibot', + 'apbct_antibot', 'apbct_anticrawler_passed', 'apbct_bot_detector_exist', 'apbct_antiflood_passed', @@ -2642,6 +2642,15 @@ function getNoCookieData() { // eslint-disable-line no-unused-vars let noCookieDataLocal = apbctLocalStorage.getCleanTalkData(); let noCookieDataSession = apbctSessionStorage.getCleanTalkData(); let noCookieData = {...noCookieDataLocal, ...noCookieDataSession}; + + // Bot detector browser state is transferred with the hidden field on the NoCookie mode + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + noCookieData[browserState.key] = browserState.value; + } + } + noCookieData = JSON.stringify(noCookieData); return '_ct_no_cookie_data_' + btoa(unescape(encodeURIComponent(noCookieData))); @@ -2669,7 +2678,21 @@ function getCleanTalkStorageDataArray() { // eslint-disable-line no-unused-vars noCookieDataFromUserActivity = {collecting_user_activity_data: collectingUserActivityData}; } - return {...noCookieDataLocal, ...noCookieDataSession, ...noCookieDataTypo, ...noCookieDataFromUserActivity}; + let browserStateData = {}; + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + browserStateData[browserState.key] = browserState.value; + } + } + + return { + ...noCookieDataLocal, + ...noCookieDataSession, + ...noCookieDataTypo, + ...noCookieDataFromUserActivity, + ...browserStateData, + }; } /** @@ -3314,6 +3337,9 @@ class ApbctHandler { const eventTokenKey = useUnwrappedCleantalkKeys ? 'ct_bot_detector_event_token' : 'data%5Bct_bot_detector_event_token%5D'; + const browserStateKey = useUnwrappedCleantalkKeys ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; if (!( +ctPublic.bot_detector_enabled && @@ -3338,6 +3364,12 @@ class ApbctHandler { } } + const browserState = apbctGetBrowserStatePair(); + if (browserState && body.indexOf('apbct_browser_state') === -1) { + addidionalCleantalkData += '&' + browserStateKey + '=' + + encodeURIComponent(browserState.value); + } + body += addidionalCleantalkData; } @@ -3354,6 +3386,11 @@ class ApbctHandler { body.append('ct_bot_detector_event_token', eventToken); } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState && !body.has(browserState.key)) { + body.append(browserState.key, browserState.value); + } } if (isNeedToAddCleantalkDataCheckJsonData) { @@ -3391,6 +3428,22 @@ class ApbctHandler { } } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + try { + const bodyObj = JSON.parse(body); + if ( + bodyObj && typeof bodyObj === 'object' && + !Object.prototype.hasOwnProperty.call(bodyObj, browserState.key) + ) { + bodyObj[browserState.key] = browserState.value; + body = JSON.stringify(bodyObj); + } + } catch (e) { + // body is not JSON — leave as is + } + } } return originalSend.apply(this, [body]); @@ -3448,6 +3501,11 @@ class ApbctHandler { } else { args[1].body.append('ct_no_cookie_hidden_field', getNoCookieData()); } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + args[1].body.append(browserState.key, browserState.value); + } } } } catch (e) { @@ -3504,6 +3562,22 @@ class ApbctHandler { * @return {string|FormData} Modified body. */ const attachFieldsToBody = function(body, fieldPair = false) { + const fieldPairs = [fieldPair, apbctGetBrowserStatePair()]; + + for (const pair of fieldPairs) { + body = attachFieldPairToBody(body, pair); + } + + return body; + }; + + /** + * Attach a single key/value pair to fetch request body + * @param {string|FormData} body Fetch request data body. + * @param {object|bool} fieldPair Key value to inject. + * @return {string|FormData} Modified body. + */ + const attachFieldPairToBody = function(body, fieldPair = false) { if (fieldPair) { if (body instanceof FormData || typeof body.append === 'function') { body.append(fieldPair.key, fieldPair.value); @@ -3761,255 +3835,1041 @@ class ApbctHandler { // Continue even if error } } - - // === WooCommerce add to cart (direct add-item URL) === - if ( - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/cart/add-item') - ) { - try { - if (+ctPublic.settings__forms__wc_add_to_cart) { - args[1].body = attachFieldsToBody( - args[1].body, - selectFieldsData(+ctPublic.bot_detector_enabled), - ); - } - } catch (e) { - // Continue even if error + + // === WooCommerce add to cart (direct add-item URL) === + if ( + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/cart/add-item') + ) { + try { + if (+ctPublic.settings__forms__wc_add_to_cart) { + args[1].body = attachFieldsToBody( + args[1].body, + selectFieldsData(+ctPublic.bot_detector_enabled), + ); + } + } catch (e) { + // Continue even if error + } + } + + // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === + if ( + +ctPublic.settings__forms__wc_add_to_cart && + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/batch') && + typeof args[1].body === 'string' + ) { + try { + const batchPayload = JSON.parse(args[1].body); + if (batchPayload.requests && Array.isArray(batchPayload.requests)) { + const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); + const browserState = apbctGetBrowserStatePair(); + for (const req of batchPayload.requests) { + const isAddItem = req.path === '/wc/store/v1/cart/add-item'; + if (isAddItem && req.body && fieldPair && fieldPair.key) { + req.body[fieldPair.key] = fieldPair.value; + } + if (isAddItem && req.body && browserState) { + req.body[browserState.key] = browserState.value; + } + } + args[1].body = JSON.stringify(batchPayload); + } + } catch (e) { + // Continue even if error + } + } + + // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === + preventOriginalFetch = await processIframeCommonFetch(url, args); + + // Return original fetch result if not prevented + if (!preventOriginalFetch) { + return originalFetch.apply(this, args); + } + } catch (error) { + // In case of any error in our interceptor, call original fetch + return originalFetch.apply(this, args); + } + }; + } + + /** + * Prepare jQuery.ajaxPrefilter to add CleanTalk data to jQuery ajax requests. + * Notes: + * - ajaxSetup.beforeSend is not used: a request can supply its own beforeSend and drop the default. + * - ajaxPrefilter runs for every jQuery ajax call after options are merged, so injection is guaranteed. + * - Form signs are checked on the request data/url at send time. + * - Any sign of the form HTML of the caller is insignificant in this process. + * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script + * will work independing if jQuery is loaded by CleanTalk or not + * @return {void} + */ + catchJqueryAjax() { + if ( typeof jQuery !== 'undefined' && typeof jQuery.ajaxPrefilter === 'function' ) { + jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { + const handler = new ApbctHandler(); + const sourceSign = handler.searchSignsForJQAjaxInjection(options, originalOptions); + if (sourceSign.found !== false) { + options.data = handler.injectCleantalkDataToJQAjax( + sourceSign, + handler.getJQAjaxPayloadForInject(options, originalOptions), + options, + ); + } + }); + } + } + + /** + * jQuery.param() on URLSearchParams/FormData can collapse options.data to "". + * Sign search already falls back to originalOptions; inject must use that payload too. + * @param {object} options + * @param {object=} originalOptions + * @return {*} + */ + getJQAjaxPayloadForInject(options, originalOptions) { + const current = options && options.data; + const original = originalOptions && originalOptions.data; + if ( this.jqAjaxPayloadWasCollapsed(current, original) ) { + return original; + } + return current; + } + + /** + * @param {*} current + * @param {*} original + * @return {boolean} + */ + jqAjaxPayloadWasCollapsed(current, original) { + if ( original === null || typeof original === 'undefined' ) { + return false; + } + if ( current === original ) { + return false; + } + const currentEmpty = current === '' || current === null || typeof current === 'undefined'; + if ( !currentEmpty ) { + return false; + } + if ( typeof original === 'string' ) { + return original !== ''; + } + return this.isJQAjaxFormData(original) || + this.isJQAjaxURLSearchParams(original) || + this.isJQAjaxPlainObjectOrArray(original); + } + + /** + * Normalize jQuery ajax data to a query string for sign search. + * Objects and serializeArray are read structurally so search never calls jQuery.param. + * Also reads known sign fields from the URL (IE11 FormData cannot be enumerated). + * @param {object} ajaxObject Ajax options object. + * @return {string} + */ + getJQAjaxDataAsString(ajaxObject) { + if ( !ajaxObject || typeof ajaxObject !== 'object' ) { + return ''; + } + let fromData = ''; + if ( typeof ajaxObject.data === 'string' ) { + fromData = ajaxObject.data; + } else if ( this.isJQAjaxPlainObjectOrArray(ajaxObject.data) ) { + fromData = this.getStructuredJQAjaxSignString(ajaxObject.data); + } else if ( this.isJQAjaxURLSearchParams(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } else if ( this.isJQAjaxFormData(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } + // Native IE11 FormData is write-only (no get/forEach/entries). Signs then come from the URL. + const fromUrl = this.collectKnownSignStringFromUrl(ajaxObject.url); + if ( fromData && fromUrl ) { + return fromData + '&' + fromUrl; + } + return fromData || fromUrl; + } + + /** + * Build a sign string from top-level fields without serializing the whole payload. + * @param {object|Array} data + * @return {string} + */ + getStructuredJQAjaxSignString(data) { + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return this.getSerializeArraySignString(data); + } + const parts = []; + const action = this.getPlainObjectSignField(data, 'action'); + if ( typeof action === 'string' && action !== '' ) { + parts.push('action=' + action); + } + const nonce = this.getPlainObjectSignField(data, 'ur_frontend_form_nonce'); + if ( nonce !== null ) { + parts.push('ur_frontend_form_nonce=' + nonce); + } + if ( this.plainObjectHasTwtCcSignup(data) ) { + parts.push('twt_cc_signup=1'); + } + return parts.join('&'); + } + + /** + * Read action/nonce from top-level, data[key], or nested data.key. + * @param {object} data + * @param {string} key + * @return {string|number|null} + */ + getPlainObjectSignField(data, key) { + if ( !data || typeof data !== 'object' ) { + return null; + } + if ( this.isJQAjaxScalarSignValue(data[key]) ) { + return data[key]; + } + const bracketKey = 'data[' + key + ']'; + if ( this.isJQAjaxScalarSignValue(data[bracketKey]) ) { + return data[bracketKey]; + } + if ( + data.data && + typeof data.data === 'object' && + Object.prototype.toString.call(data.data) !== '[object Array]' && + this.isJQAjaxScalarSignValue(data.data[key]) + ) { + return data.data[key]; + } + return null; + } + + /** + * @param {*} value + * @return {boolean} + */ + isJQAjaxScalarSignValue(value) { + return typeof value === 'string' || typeof value === 'number'; + } + + /** + * @param {object} data + * @param {number=} depth + * @return {boolean} + */ + plainObjectHasTwtCcSignup(data, depth) { + if ( !data || typeof data !== 'object' ) { + return false; + } + if ( typeof depth === 'undefined' ) { + depth = 0; + } + if ( depth > 2 ) { + return false; + } + for ( const key in data ) { + if ( !Object.prototype.hasOwnProperty.call(data, key) ) { + continue; + } + const normalizedKey = this.unwrapJQAjaxFormDataKey(key); + if ( normalizedKey === 'twt_cc_signup' || key.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + const value = data[key]; + if ( typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + if ( + value && + typeof value === 'object' && + Object.prototype.toString.call(value) !== '[object Array]' + ) { + if ( this.plainObjectHasTwtCcSignup(value, depth + 1) ) { + return true; + } + } + } + return false; + } + + /** + * @param {Array} entries + * @return {string} + */ + getSerializeArraySignString(entries) { + const parts = []; + for ( let i = 0; i < entries.length; i++ ) { + const entry = entries[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + continue; + } + const value = entry.value; + const normalizedKey = this.unwrapJQAjaxFormDataKey(entry.name); + if ( this.isJQAjaxKnownSignField(normalizedKey, value) ) { + parts.push(normalizedKey + '=' + value); + } + } + return parts.join('&'); + } + + /** + * True for serializeArray payloads, including an empty array. + * @param {Array} data + * @return {boolean} + */ + isJQAjaxSerializeArray(data) { + if ( Object.prototype.toString.call(data) !== '[object Array]' ) { + return false; + } + for ( let i = 0; i < data.length; i++ ) { + const entry = data[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + return false; + } + } + return true; + } + + /** + * Cross-realm URLSearchParams (instanceof fails across windows). + * @param {*} data + * @return {boolean} + */ + isJQAjaxURLSearchParams(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object URLSearchParams]' ) { + return true; + } + if ( tag === '[object FormData]' ) { + return false; + } + return typeof data.sort === 'function' && typeof data.get === 'function'; + } + + /** + * Cross-realm FormData, including common polyfills. + * @param {*} data + * @return {boolean} + */ + isJQAjaxFormData(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) || this.isJQAjaxURLSearchParams(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object FormData]' ) { + return true; + } + if ( tag === '[object Headers]' || typeof data.getSetCookie === 'function' ) { + return false; + } + return typeof data.forEach === 'function' || + typeof data.get === 'function' || + typeof data.entries === 'function'; + } + + /** + * Collect only known sign fields from FormData / URLSearchParams. + * Unwrap data[action] so later action=... checks match. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + collectKnownSignStringFromKeyValueBag(bag) { + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' ) { + return; + } + const valueAsString = String(value); + const normalizedKey = unwrapKey(key); + if ( + knownKeys[normalizedKey] || + valueAsString.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + valueAsString); + } + }); + if ( collected ) { + return parts.join('&'); + } + if ( typeof bag.get !== 'function' ) { + return ''; + } + const keysToProbe = [ + 'action', + 'ur_frontend_form_nonce', + 'twt_cc_signup', + ]; + const getParts = []; + for ( let i = 0; i < keysToProbe.length; i++ ) { + const key = keysToProbe[i]; + const value = this.getFormDataScalarValue(bag, [key, 'data[' + key + ']']); + if ( value !== null ) { + getParts.push(key + '=' + value); + } + } + return getParts.join('&'); + } + + /** + * Known sign fields from a request URL query. IE11-safe (no URLSearchParams). + * @param {string} url + * @return {string} + */ + collectKnownSignStringFromUrl(url) { + if ( typeof url !== 'string' || url === '' ) { + return ''; + } + const queryIndex = url.indexOf('?'); + if ( queryIndex === -1 || queryIndex === url.length - 1 ) { + return ''; + } + const hashIndex = url.indexOf('#', queryIndex); + const query = hashIndex === -1 ? + url.slice(queryIndex + 1) : + url.slice(queryIndex + 1, hashIndex); + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const pairs = query.split('&'); + for ( let i = 0; i < pairs.length; i++ ) { + const pair = pairs[i]; + if ( !pair ) { + continue; + } + const eq = pair.indexOf('='); + let rawKey = eq === -1 ? pair : pair.slice(0, eq); + let rawValue = eq === -1 ? '' : pair.slice(eq + 1); + try { + rawKey = decodeURIComponent(rawKey.replace(/\+/g, ' ')); + rawValue = decodeURIComponent(rawValue.replace(/\+/g, ' ')); + } catch (e) { + continue; + } + const normalizedKey = unwrapKey(rawKey); + if ( + knownKeys[normalizedKey] || + rawValue.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + rawValue); + } + } + return parts.join('&'); + } + + /** + * Walk FormData/URLSearchParams via forEach, then entries() for polyfills that only have an iterator. + * @param {FormData|URLSearchParams} bag + * @param {Function} callback + * @return {boolean} + */ + forEachJQAjaxKeyValueBag(bag, callback) { + if ( typeof bag.forEach === 'function' ) { + try { + bag.forEach(callback); + return true; + } catch (e) { + // Fall through to entries(). + } + } + if ( typeof bag.entries !== 'function' ) { + return false; + } + try { + const iterator = bag.entries(); + if ( !iterator || typeof iterator.next !== 'function' ) { + return false; + } + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + callback(pair[1], pair[0]); + } + step = iterator.next(); + } + return true; + } catch (e) { + return false; + } + } + + /** + * @return {Object} + */ + getJQAjaxKnownSignKeys() { + const knownKeys = Object.create(null); + knownKeys.action = true; + knownKeys.ur_frontend_form_nonce = true; + knownKeys.twt_cc_signup = true; + return knownKeys; + } + + /** + * @param {string} normalizedKey + * @param {*} value + * @return {boolean} + */ + isJQAjaxKnownSignField(normalizedKey, value) { + if ( + normalizedKey === 'action' || + normalizedKey === 'ur_frontend_form_nonce' || + normalizedKey === 'twt_cc_signup' || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + return true; + } + return typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1; + } + + /** + * Treat data[action] as action for WP-style payloads. + * @param {string} key + * @return {string} + */ + unwrapJQAjaxFormDataKey(key) { + if ( typeof key !== 'string' ) { + return ''; + } + if ( key.length > 6 && key.indexOf('data[') === 0 && key.charAt(key.length - 1) === ']' ) { + return key.slice(5, -1); + } + return key; + } + + /** + * @param {FormData} formData + * @param {Array.} keys + * @return {string|number|null} + */ + getFormDataScalarValue(formData, keys) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && (typeof value === 'string' || typeof value === 'number') ) { + return value; + } + } + return null; + } + + /** + * True for arrays and plain objects that jQuery.param can serialize safely. + * @param {*} data + * @return {boolean} + */ + isJQAjaxPlainObjectOrArray(data) { + if ( data === null || typeof data !== 'object' ) { + return false; + } + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return true; + } + if ( typeof jQuery !== 'undefined' && typeof jQuery.isPlainObject === 'function' ) { + return jQuery.isPlainObject(data); + } + const proto = Object.getPrototypeOf(data); + return proto === Object.prototype || proto === null; + } + + /** + * Search for sign within AJAX data to do inject CleanTalk data. + * @param {object} ajaxObject Ajax object. + * @param {object=} originalOptions Original jQuery ajax options before merge. + * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + */ + searchSignsForJQAjaxInjection(ajaxObject, originalOptions) { + let sourceSign = { + 'found': false, + 'keepUnwrapped': false, + 'attachVisibleFieldsData': false, + }; + let dataString = this.getJQAjaxDataAsString(ajaxObject); + if ( !dataString && originalOptions && originalOptions !== ajaxObject ) { + dataString = this.getJQAjaxDataAsString(originalOptions); + } + + if ( dataString.indexOf('action=fl_builder_subscribe_form_submit') !== -1 ) { + sourceSign.found = 'fl_builder_subscribe_form_submit'; + } + if ( dataString.indexOf('twt_cc_signup') !== -1 ) { + sourceSign.found = 'twt_cc_signup'; + } + if ( dataString.indexOf('action=mailpoet') !== -1 ) { + sourceSign.found = 'action=mailpoet'; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=user_registration') !== -1 && + dataString.indexOf('ur_frontend_form_nonce') !== -1 + ) { + sourceSign.found = 'action=user_registration'; + } + if ( dataString.indexOf('action=happyforms_message') !== -1 ) { + sourceSign.found = 'action=happyforms_message'; + } + if ( dataString.indexOf('action=new_activity_comment') !== -1 ) { + sourceSign.found = 'action=new_activity_comment'; + } + if ( dataString.indexOf('action=wwlc_create_user') !== -1 ) { + sourceSign.found = 'action=wwlc_create_user'; + } + if ( dataString.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 ) { + sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=drplus_signup') !== -1 ) { + sourceSign.found = 'action=drplus_signup'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=bt_cc') !== -1 ) { + sourceSign.found = 'action=bt_cc'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=wpr_form_builder_email') !== -1 ) { + sourceSign.found = 'action=wpr_form_builder_email'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=nf_ajax_submit') !== -1 ) { + sourceSign.found = 'action=nf_ajax_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=uael_register_user') !== -1 && + ctPublic.data__cookies_type === 'none' + ) { + sourceSign.found = 'action=uael_register_user'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=SQBSubmitQuizAjax') !== -1 ) { + sourceSign.found = 'action=SQBSubmitQuizAjax'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=user_registration_user_form_submit') !== -1 ) { + sourceSign.found = 'action=user_registration_user_form_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=bloom_subscribe') !== -1 ) { + sourceSign.found = 'action=bloom_subscribe'; + sourceSign.keepUnwrapped = true; + } + if ( + this.isJQAjaxFormData(ajaxObject.data) && + typeof ajaxObject.data.get === 'function' && + ajaxObject.data.get('action') === 'pafe_ajax_form_builder' + ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } else if ( dataString.indexOf('action=pafe_ajax_form_builder') !== -1 ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } + + // woocommerce add to cart is based on URL + if ( typeof ajaxObject.url === 'string' && ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1 ) { + sourceSign.found = 'wc-ajax=add_to_cart'; + // GET/HEAD: PHP reads Get::get('ct_bot_detector_event_token'), not data[...]. + if ( this.isJQAjaxNoContentMethod(ajaxObject) ) { + sourceSign.keepUnwrapped = true; + } + } + + return sourceSign; + } + + /** + * Inject CleanTalk data into jQuery ajax payload of any supported type. + * @param {object} sourceSign + * @param {*} ajaxData + * @param {object=} ajaxOptions jQuery ajax options (traditional, processData, contentType). + * Keep URLSearchParams/objects when processData or contentType is false. + * URLSearchParams must also disable processData, or jQuery.param() later yields "". + * GET/HEAD never keep the original type: jQuery only puts string data on the URL. + * @return {*} + */ + injectCleantalkDataToJQAjax(sourceSign, ajaxData, ajaxOptions) { + const traditional = ajaxOptions && ajaxOptions.traditional; + const keepOriginalType = !this.isJQAjaxNoContentMethod(ajaxOptions) && !!(ajaxOptions && ( + ajaxOptions.processData === false || + ajaxOptions.contentType === false + )); + + if ( ajaxData === null || typeof ajaxData === 'undefined' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ''); + } + if ( typeof ajaxData === 'string' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData); + } + if ( this.isJQAjaxPlainObjectOrArray(ajaxData) ) { + if ( keepOriginalType ) { + if ( Object.prototype.toString.call(ajaxData) === '[object Array]' ) { + if ( this.isJQAjaxSerializeArray(ajaxData) ) { + return this.injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData); + } + return ajaxData; + } + return this.injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData); + } + try { + if ( typeof jQuery !== 'undefined' && typeof jQuery.param === 'function' ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + jQuery.param(ajaxData, traditional), + ); + } + } catch (e) { + return ajaxData; + } + return ajaxData; + } + if ( this.isJQAjaxURLSearchParams(ajaxData) ) { + if ( keepOriginalType ) { + this.preserveJQAjaxURLSearchParamsOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxKeyValue( + sourceSign, + this.cloneURLSearchParams(ajaxData), + ); + } + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData.toString()); + } + if ( this.isJQAjaxFormData(ajaxData) ) { + if ( this.isJQAjaxNoContentMethod(ajaxOptions) ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + this.serializeJQAjaxKeyValueBag(ajaxData), + ); + } + this.preserveJQAjaxFormDataOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxFormData( + sourceSign, + this.cloneFormData(ajaxData), + ); + } + return ajaxData; + } + + /** + * GET/HEAD have no body. Missing type is GET (jQuery default). + * @param {object=} ajaxOptions + * @return {boolean} + */ + isJQAjaxNoContentMethod(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return false; + } + const type = ajaxOptions.type || ajaxOptions.method; + if ( typeof type !== 'string' || type === '' ) { + return true; + } + const method = type.toUpperCase(); + return method === 'GET' || method === 'HEAD'; + } + + /** + * Collect CleanTalk fields to append to a key/value payload. + * @param {object} sourceSign + * @return {Array.>} + */ + getCleantalkJQAjaxFieldPairs(sourceSign) { + const pairs = []; + const wrapKey = function(key) { + return sourceSign.keepUnwrapped ? key : 'data[' + key + ']'; + }; + + if ( + +ctPublic.bot_detector_enabled && + apbctLocalStorage.get('bot_detector_event_token') + ) { + const token = this.toolGetEventToken(); + if ( token ) { + pairs.push([wrapKey('ct_bot_detector_event_token'), token]); + } + } else { + const noCookieData = getNoCookieData(); + if ( noCookieData ) { + pairs.push([wrapKey('ct_no_cookie_hidden_field'), noCookieData]); + } + } + + const browserState = apbctGetBrowserStatePair(); + if ( browserState ) { + const browserStateKey = sourceSign.keepUnwrapped ? + browserState.key : + 'data[' + browserState.key + ']'; + pairs.push([browserStateKey, browserState.value]); + } + + return pairs; + } + + /** + * jQuery.param(FormData) after the prefilter yields "". Keep the body as FormData. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxFormDataOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + ajaxOptions.contentType = false; + } + + /** + * jQuery.param(URLSearchParams) after the prefilter yields "". Keep the body as URLSearchParams. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxURLSearchParamsOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + } + + /** + * Read a FormData field via get(), forEach(), or entries(). + * Native IE11 FormData is write-only and cannot be read. + * @param {FormData} formData + * @param {Array.} keys + * @return {*} + */ + getFormDataField(formData, keys) { + if ( typeof formData.get === 'function' ) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && typeof value !== 'undefined' ) { + return value; + } + } + } + if ( typeof formData.forEach === 'function' ) { + let found = null; + formData.forEach(function(value, key) { + if ( found !== null ) { + return; + } + for ( let i = 0; i < keys.length; i++ ) { + if ( key === keys[i] ) { + found = value; + return; } } - - // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === - if ( - +ctPublic.settings__forms__wc_add_to_cart && - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/batch') && - typeof args[1].body === 'string' - ) { - try { - const batchPayload = JSON.parse(args[1].body); - if (batchPayload.requests && Array.isArray(batchPayload.requests)) { - const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); - for (const req of batchPayload.requests) { - const isAddItem = req.path === '/wc/store/v1/cart/add-item'; - if (isAddItem && req.body && fieldPair && fieldPair.key) { - req.body[fieldPair.key] = fieldPair.value; + }); + if ( found !== null ) { + return found; + } + } + if ( typeof formData.entries === 'function' ) { + try { + const iterator = formData.entries(); + if ( iterator && typeof iterator.next === 'function' ) { + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + for ( let i = 0; i < keys.length; i++ ) { + if ( pair[0] === keys[i] ) { + return pair[1]; } } - args[1].body = JSON.stringify(batchPayload); } - } catch (e) { - // Continue even if error + step = iterator.next(); } } - - // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === - preventOriginalFetch = await processIframeCommonFetch(url, args); - - // Return original fetch result if not prevented - if (!preventOriginalFetch) { - return originalFetch.apply(this, args); - } - } catch (error) { - // In case of any error in our interceptor, call original fetch - return originalFetch.apply(this, args); + } catch (e) { + return null; } - }; + } + return null; } /** - * Prepare jQuery.ajaxSetup to add nocookie data to the jQuery ajax request. - * Notes: - * - Do it just once, the ajaxSetup.beforeSend will be overwritten for any calls. - * - Signs of forms need to be caught will be checked during ajaxSetup.settings.data process on send. - * - Any sign of the form HTML of the caller is insignificant in this process. - * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script - * will work independing if jQuery is loaded by CleanTalk or not - * @return {void} + * Clone URLSearchParams so the caller's instance is not mutated. + * @param {URLSearchParams} params + * @return {URLSearchParams} */ - catchJqueryAjax() { - if ( typeof jQuery !== 'undefined') { - // this code run on base ajax rules - so do not work due scripts use it's own ajax object injections - if ( typeof jQuery.ajaxSetup === 'function' ) { - jQuery.ajaxSetup({ - beforeSend: function(xhr, settings) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(settings, 'ajaxSetup'); - if (sourceSign.found !== false) { - settings.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, settings.data); - } - }, - }); + cloneURLSearchParams(params) { + const serialized = typeof params.toString === 'function' ? params.toString() : ''; + if ( typeof params.constructor === 'function' && params.constructor !== Object ) { + try { + return new params.constructor(serialized); + } catch (e) { + // Fall through to the current-window constructor. } - // this code run on ANY ajax on ANY script queue status - // todo Probably move all ajaxSetup actions to ajaxPrefilter - if ( typeof jQuery.ajaxPrefilter === 'function' ) { - jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(options, 'ajaxPrefilter'); - if (sourceSign.found !== false) { - if (typeof options.data === 'string') { - options.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, options.data); - } - if ( - typeof options.data === 'object' && - typeof options.data.append === 'function' - ) { - options.data = handler.injectCleantalkDataToJQAjaxFormData(sourceSign, options.data); - } - } - }); + } + if ( typeof URLSearchParams === 'function' ) { + try { + return new URLSearchParams(serialized); + } catch (e) { + return params; } } + return params; } /** - * Search for sign within AJAX data to do inject CleanTalk data. - * @param {object} ajaxObject Ajax object. - * @param {string} catchOn Function should be catched on. - * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + * Clone FormData when it can be enumerated (forEach or entries); otherwise reuse. + * @param {FormData} formData + * @return {FormData} */ - searchSignsForJQAjaxInjection(ajaxObject, catchOn = 'ajaxSetup') { - let sourceSign = { - 'found': false, - 'keepUnwrapped': false, - 'attachVisibleFieldsData': false, - }; - // on ajaxSetup - if (catchOn === 'ajaxSetup') { - // settings data is string (important!) - if ( typeof ajaxObject.data === 'string' ) { - if ( - ajaxObject.data.indexOf('action=fl_builder_subscribe_form_submit') !== -1 - ) { - sourceSign.found = 'fl_builder_subscribe_form_submit'; - } - if ( - ajaxObject.data.indexOf('twt_cc_signup') !== -1 - ) { - sourceSign.found = 'twt_cc_signup'; - } - if ( - ajaxObject.data.indexOf('action=mailpoet') !== -1 - ) { - sourceSign.found = 'action=mailpoet'; - sourceSign.attachVisibleFieldsData = true; - } - - if ( - ajaxObject.data.indexOf('action=user_registration') !== -1 && - ajaxObject.data.indexOf('ur_frontend_form_nonce') !== -1 - ) { - sourceSign.found = 'action=user_registration'; - } - - if (ajaxObject.data.indexOf('action=happyforms_message') !== -1) { - sourceSign.found = 'action=happyforms_message'; - } + cloneFormData(formData) { + try { + const clone = new FormData(); + const copied = this.forEachJQAjaxKeyValueBag(formData, function(value, key) { + clone.append(key, value); + }); + if ( copied ) { + return clone; + } + } catch (e) { + return formData; + } + return formData; + } - if ( - ajaxObject.data.indexOf('action=new_activity_comment') !== -1 - ) { - sourceSign.found = 'action=new_activity_comment'; - } - if ( - ajaxObject.data.indexOf('action=wwlc_create_user') !== -1 - ) { - sourceSign.found = 'action=wwlc_create_user'; - } - if ( - ajaxObject.data.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 - ) { - sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=drplus_signup') !== -1 - ) { - sourceSign.found = 'action=drplus_signup'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=bt_cc') !== -1 - ) { - sourceSign.found = 'action=bt_cc'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=wpr_form_builder_email') !== -1 - ) { - sourceSign.found = 'action=wpr_form_builder_email'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=nf_ajax_submit') !== -1 - ) { - sourceSign.found = 'action=nf_ajax_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=uael_register_user') !== -1 && - ctPublic.data__cookies_type === 'none' - ) { - sourceSign.found = 'action=uael_register_user'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=SQBSubmitQuizAjax') !== -1 - ) { - sourceSign.found = 'action=SQBSubmitQuizAjax'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=user_registration_user_form_submit') !== -1 - ) { - sourceSign.found = 'action=user_registration_user_form_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } + /** + * Form-urlencoded string from FormData/URLSearchParams. Skip File/Blob values. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + serializeJQAjaxKeyValueBag(bag) { + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { + return; } - // wooocommerce add to cart is based on URL - if ( typeof ajaxObject.url === 'string' ) { - if (ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1) { - sourceSign.found = 'wc-ajax=add_to_cart'; + parts.push(encodeURIComponent(String(key)) + '=' + encodeURIComponent(String(value))); + }); + if ( collected ) { + return parts.join('&'); + } + return ''; + } + + /** + * Inject CleanTalk fields into URLSearchParams without changing the payload type. + * @param {object} sourceSign + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + injectCleantalkDataToJQAjaxKeyValue(sourceSign, params) { + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + params.append(pairs[i][0], pairs[i][1]); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( extractor ) { + const extracted = extractor.extract(params.toString()); + if ( typeof extracted === 'string' ) { + params.append('apbct_visible_fields', extracted); } } } + return params; + } - // on ajaxPrefilter - if (catchOn === 'ajaxPrefilter') { - if (typeof ajaxObject.data === 'string') { - if (ajaxObject.data.indexOf('action=bloom_subscribe') !== -1) { - sourceSign.found = 'action=bloom_subscribe'; - sourceSign.keepUnwrapped = true; + /** + * Inject CleanTalk fields into a jQuery serializeArray payload. + * @param {object} sourceSign + * @param {Array} ajaxData + * @return {Array} + */ + injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData) { + const result = ajaxData.slice(); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result.push({ + name: pairs[i][0], + value: pairs[i][1], + }); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' + ) { + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.push({ + name: 'apbct_visible_fields', + value: extracted, + }); } } + } + return result; + } + /** + * Inject CleanTalk fields into a plain object without changing the payload type. + * @param {object} sourceSign + * @param {object} ajaxData + * @return {object} + */ + injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData) { + const result = typeof jQuery !== 'undefined' && typeof jQuery.extend === 'function' ? + jQuery.extend({}, ajaxData) : + this.clonePlainObject(ajaxData); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result[pairs[i][0]] = pairs[i][1]; + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); if ( - typeof ajaxObject.data === 'object' && - ajaxObject.data !== null && - typeof ajaxObject.data.get === 'function' + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' ) { - if (ajaxObject.data.get('action') === 'pafe_ajax_form_builder') { - sourceSign.found = 'action=pafe_ajax_form_builder'; - sourceSign.keepUnwrapped = true; + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.apbct_visible_fields = extracted; } } } + return result; + } - return sourceSign; + /** + * IE11-safe shallow copy of a plain object. + * @param {object} ajaxData + * @return {object} + */ + clonePlainObject(ajaxData) { + const result = {}; + for ( const key in ajaxData ) { + if ( Object.prototype.hasOwnProperty.call(ajaxData, key) ) { + result[key] = ajaxData[key]; + } + } + return result; } /** @@ -4021,8 +4881,7 @@ class ApbctHandler { injectCleantalkDataToJQAjaxFormData(sourceSign, ajaxDataFormData) { if ( typeof sourceSign !== 'object' || - typeof ajaxDataFormData !== 'object' || - !(ajaxDataFormData instanceof FormData) + !this.isJQAjaxFormData(ajaxDataFormData) ) { return ajaxDataFormData; } @@ -4053,6 +4912,16 @@ class ApbctHandler { } } + // Bot detector browser state + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append(browserState.key, browserState.value); + } else { + ajaxDataFormData.append('data[' + browserState.key + ']', browserState.value); + } + } + // Visible fields if (sourceSign.attachVisibleFieldsData) { let visibleFieldsSearchResult = false; @@ -4060,13 +4929,10 @@ class ApbctHandler { if (extractor) { // Try to find form_id in FormData to find form container and // collect visible fields only inside it - let formId = null; - for (let pair of ajaxDataFormData.entries()) { - if (pair[0] === 'form_id' || pair[0] === 'data[form_id]') { - formId = pair[1]; - break; - } - } + const formId = this.getFormDataField( + ajaxDataFormData, + ['form_id', 'data[form_id]'], + ); let container = null; if (formId && typeof formId === 'string') { // Sanitize formId to prevent selector injection @@ -4111,6 +4977,15 @@ class ApbctHandler { let eventToken = ''; let noCookieData = ''; let visibleFieldsString = ''; + let browserStateString = ''; + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + const browserStateKey = sourceSign.keepUnwrapped ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; + browserStateString = browserStateKey + '=' + encodeURIComponent(browserState.value) + '&'; + } if ( +ctPublic.bot_detector_enabled && @@ -4127,9 +5002,9 @@ class ApbctHandler { } else { noCookieData = getNoCookieData(); if (sourceSign.keepUnwrapped) { - noCookieData = 'ct_no_cookie_hidden_field=' + noCookieData + '&'; + noCookieData = 'ct_no_cookie_hidden_field=' + encodeURIComponent(noCookieData) + '&'; } else { - noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + noCookieData + '&'; + noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + encodeURIComponent(noCookieData) + '&'; } } @@ -4152,7 +5027,7 @@ class ApbctHandler { } } - return noCookieData + eventToken + visibleFieldsString + ajaxDataString; + return noCookieData + eventToken + browserStateString + visibleFieldsString + ajaxDataString; } /** @@ -7073,67 +7948,126 @@ function apbctCancelAutocomplete(element) { })); } -let botDetectorLogLastUpdate = 0; -let botDetectorLogEventTypesCollected = []; - -// bot_detector frontend_data log alt session saving cron -if ( - ctPublicFunctions.hasOwnProperty('bot_detector_enabled') && - +ctPublicFunctions.bot_detector_enabled && - ctPublicFunctions.hasOwnProperty('data__frontend_data_log_enabled') && - ctPublicFunctions.data__frontend_data_log_enabled == 1 -) { - sendBotDetectorLogToAltSessions(1000); -} - /** - * Send BotDetector logs data to alternative sessions. - * If log_last_update has changed and log contains new event types, the log will be sent to the alternative sessions. - * @param {int} cronStartTimeout delay before cron start - * @param {int} interval check fires on interval + * Bot detector browser state. + * + * The state is passed to the site backend with the current JS->PHP transport and goes + * to the moderate request as sender_info.bot_detector_frontend_data_log. */ -function sendBotDetectorLogToAltSessions(cronStartTimeout = 3000, interval = 1000) { - setTimeout(function() { - setInterval(function() { - const currentLog = apbctLocalStorage.get('ct_bot_detector_frontend_data_log'); - if (needsSaveLogToAltSessions(currentLog)) { - botDetectorLogLastUpdate = currentLog.log_last_update; - // the log will be taken from javascriptclientdata - ctSetAlternativeCookie([], {forceAltCookies: true}); - } - }, interval); - }, cronStartTimeout); -} +class ApbctBrowserState { + static STATE_KEY = 'apbct_browser_state'; + static LOG_KEY = 'ct_bot_detector_frontend_data_log'; + static SCRIPT_SIGNS = { + botd_wrapper_loaded: 'ct-bot-detector-wrapper', + botd_logic_loaded: 'ct-bot-detector.min', + }; + /** + * This LS key is set on bot-detector side + * @type {string} + */ + static TRANSPORT_ENABLED_SIGN_KEY = 'bot_detector_log_transport_enabled'; + static botdWrapperLoaded = 0; + static botdLogicLoaded = 0; -/** - * Check if the log needs to be saved to the alt sessions. If the log has new event types, it will be saved. - * @param {object} currentLog - * @return {boolean} - */ -function needsSaveLogToAltSessions(currentLog) { - if ( - currentLog && currentLog.hasOwnProperty('log_last_update') && - botDetectorLogLastUpdate !== currentLog.log_last_update - ) { - try { - for (let i = 0; i < currentLog.records.length; i++) { - const currentType = currentLog.records[i].frontend_data.js_event; - // check if this event type was already collected - if (currentType !== undefined && botDetectorLogEventTypesCollected.includes(currentType)) { - continue; + /** + * Get the current browser state as a JSON string ready to be transferred. + * @return {string} Empty string if the bot detector is disabled or on any collecting error. + */ + static getFrontendDataLog() { + const prefix = (typeof ctPublicFunctions !== 'undefined' && ctPublicFunctions.cookiePrefix) ? + ctPublicFunctions.cookiePrefix : + ''; + const logKey = prefix + ApbctBrowserState.LOG_KEY; + const noPrefixLogKey = ApbctBrowserState.LOG_KEY; + + if (typeof apbctLocalStorage !== 'undefined' && apbctLocalStorage.get) { + const logObject = apbctLocalStorage.get(logKey) || apbctLocalStorage.get(noPrefixLogKey) || null; + if (logObject && typeof logObject === 'string') { + try { + return JSON.parse(logObject); + } catch (e) { + return ''; } - // add new event type to collection, this type will be sent to the alt sessions further - botDetectorLogEventTypesCollected.push(currentType); - return true; } + return logObject; + } + + let rawLog = localStorage.getItem(logKey); + if (!rawLog) { + rawLog = localStorage.getItem(noPrefixLogKey) || null; + } + + try { + return typeof rawLog === 'string' ? JSON.parse(rawLog) : rawLog; } catch (e) { - console.log('APBCT: bot detector log collection error: ' . e.toString()); + return ''; } } - return false; -} + /** + * + * @return {object} + */ + static asDTO() { + return { + botd_logic_loaded: ApbctBrowserState.botdLogicLoaded, + botd_wrapper_loaded: ApbctBrowserState.botdWrapperLoaded, + frontend_data_log: '', + transport_enabled: 1, + }; + } + + /** + * Look for the bot detector scripts in the page DOM. + * @return {boolean} True if both scripts are found. + */ + static detectScripts() { + if (ApbctBrowserState.botdWrapperLoaded && ApbctBrowserState.botdLogicLoaded) { + return true; + } + + const scripts = document.getElementsByTagName('script'); + + for (let i = 0; i < scripts.length; i++) { + const src = scripts[i].getAttribute('src'); + if (!src) { + continue; + } + if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_wrapper_loaded) !== -1) { + ApbctBrowserState.botdWrapperLoaded = 1; + } else if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_logic_loaded) !== -1) { + ApbctBrowserState.botdLogicLoaded = 1; + } + } + + // The bot detector logic sets this flag on its own start + return !!ApbctBrowserState.botdWrapperLoaded && !!ApbctBrowserState.botdLogicLoaded; + } +} +/** + * Get the browser state as a key/value pair to attach it to an intercepted request. + * @return {{key: string, value: string}|false} False if there is nothing to attach. + */ +function apbctGetBrowserStatePair() { // eslint-disable-line no-unused-vars + try { + ApbctBrowserState.detectScripts(); + let state = ApbctBrowserState.asDTO(); + if ( ApbctBrowserState.botdLogicLoaded ) { + const transportEnabled = localStorage.getItem(ApbctBrowserState.TRANSPORT_ENABLED_SIGN_KEY) === '1'; + if (transportEnabled) { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } else { + state.transport_enabled = 0; + } + } else { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } + return {key: ApbctBrowserState.STATE_KEY, value: JSON.stringify(state)}; + } catch (e) { + return false; + } +} let ctCheckedEmails = {}; let ctCheckedEmailsExist = {}; diff --git a/js/prebuild/apbct-public-bundle_full-protection.js b/js/prebuild/apbct-public-bundle_full-protection.js index 26ea6d110..6bfd6c33a 100644 --- a/js/prebuild/apbct-public-bundle_full-protection.js +++ b/js/prebuild/apbct-public-bundle_full-protection.js @@ -2253,7 +2253,7 @@ function ctSetCookie( cookies, value, expires='') { let listOfCookieNamesToForceAlt = [ 'ct_sfw_pass_key', 'ct_sfw_passed', - 'wordpress_apbct_antibot', + 'apbct_antibot', 'apbct_anticrawler_passed', 'apbct_bot_detector_exist', 'apbct_antiflood_passed', @@ -2642,6 +2642,15 @@ function getNoCookieData() { // eslint-disable-line no-unused-vars let noCookieDataLocal = apbctLocalStorage.getCleanTalkData(); let noCookieDataSession = apbctSessionStorage.getCleanTalkData(); let noCookieData = {...noCookieDataLocal, ...noCookieDataSession}; + + // Bot detector browser state is transferred with the hidden field on the NoCookie mode + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + noCookieData[browserState.key] = browserState.value; + } + } + noCookieData = JSON.stringify(noCookieData); return '_ct_no_cookie_data_' + btoa(unescape(encodeURIComponent(noCookieData))); @@ -2669,7 +2678,21 @@ function getCleanTalkStorageDataArray() { // eslint-disable-line no-unused-vars noCookieDataFromUserActivity = {collecting_user_activity_data: collectingUserActivityData}; } - return {...noCookieDataLocal, ...noCookieDataSession, ...noCookieDataTypo, ...noCookieDataFromUserActivity}; + let browserStateData = {}; + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + browserStateData[browserState.key] = browserState.value; + } + } + + return { + ...noCookieDataLocal, + ...noCookieDataSession, + ...noCookieDataTypo, + ...noCookieDataFromUserActivity, + ...browserStateData, + }; } /** @@ -3314,6 +3337,9 @@ class ApbctHandler { const eventTokenKey = useUnwrappedCleantalkKeys ? 'ct_bot_detector_event_token' : 'data%5Bct_bot_detector_event_token%5D'; + const browserStateKey = useUnwrappedCleantalkKeys ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; if (!( +ctPublic.bot_detector_enabled && @@ -3338,6 +3364,12 @@ class ApbctHandler { } } + const browserState = apbctGetBrowserStatePair(); + if (browserState && body.indexOf('apbct_browser_state') === -1) { + addidionalCleantalkData += '&' + browserStateKey + '=' + + encodeURIComponent(browserState.value); + } + body += addidionalCleantalkData; } @@ -3354,6 +3386,11 @@ class ApbctHandler { body.append('ct_bot_detector_event_token', eventToken); } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState && !body.has(browserState.key)) { + body.append(browserState.key, browserState.value); + } } if (isNeedToAddCleantalkDataCheckJsonData) { @@ -3391,6 +3428,22 @@ class ApbctHandler { } } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + try { + const bodyObj = JSON.parse(body); + if ( + bodyObj && typeof bodyObj === 'object' && + !Object.prototype.hasOwnProperty.call(bodyObj, browserState.key) + ) { + bodyObj[browserState.key] = browserState.value; + body = JSON.stringify(bodyObj); + } + } catch (e) { + // body is not JSON — leave as is + } + } } return originalSend.apply(this, [body]); @@ -3448,6 +3501,11 @@ class ApbctHandler { } else { args[1].body.append('ct_no_cookie_hidden_field', getNoCookieData()); } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + args[1].body.append(browserState.key, browserState.value); + } } } } catch (e) { @@ -3504,6 +3562,22 @@ class ApbctHandler { * @return {string|FormData} Modified body. */ const attachFieldsToBody = function(body, fieldPair = false) { + const fieldPairs = [fieldPair, apbctGetBrowserStatePair()]; + + for (const pair of fieldPairs) { + body = attachFieldPairToBody(body, pair); + } + + return body; + }; + + /** + * Attach a single key/value pair to fetch request body + * @param {string|FormData} body Fetch request data body. + * @param {object|bool} fieldPair Key value to inject. + * @return {string|FormData} Modified body. + */ + const attachFieldPairToBody = function(body, fieldPair = false) { if (fieldPair) { if (body instanceof FormData || typeof body.append === 'function') { body.append(fieldPair.key, fieldPair.value); @@ -3761,255 +3835,1041 @@ class ApbctHandler { // Continue even if error } } - - // === WooCommerce add to cart (direct add-item URL) === - if ( - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/cart/add-item') - ) { - try { - if (+ctPublic.settings__forms__wc_add_to_cart) { - args[1].body = attachFieldsToBody( - args[1].body, - selectFieldsData(+ctPublic.bot_detector_enabled), - ); - } - } catch (e) { - // Continue even if error + + // === WooCommerce add to cart (direct add-item URL) === + if ( + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/cart/add-item') + ) { + try { + if (+ctPublic.settings__forms__wc_add_to_cart) { + args[1].body = attachFieldsToBody( + args[1].body, + selectFieldsData(+ctPublic.bot_detector_enabled), + ); + } + } catch (e) { + // Continue even if error + } + } + + // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === + if ( + +ctPublic.settings__forms__wc_add_to_cart && + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/batch') && + typeof args[1].body === 'string' + ) { + try { + const batchPayload = JSON.parse(args[1].body); + if (batchPayload.requests && Array.isArray(batchPayload.requests)) { + const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); + const browserState = apbctGetBrowserStatePair(); + for (const req of batchPayload.requests) { + const isAddItem = req.path === '/wc/store/v1/cart/add-item'; + if (isAddItem && req.body && fieldPair && fieldPair.key) { + req.body[fieldPair.key] = fieldPair.value; + } + if (isAddItem && req.body && browserState) { + req.body[browserState.key] = browserState.value; + } + } + args[1].body = JSON.stringify(batchPayload); + } + } catch (e) { + // Continue even if error + } + } + + // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === + preventOriginalFetch = await processIframeCommonFetch(url, args); + + // Return original fetch result if not prevented + if (!preventOriginalFetch) { + return originalFetch.apply(this, args); + } + } catch (error) { + // In case of any error in our interceptor, call original fetch + return originalFetch.apply(this, args); + } + }; + } + + /** + * Prepare jQuery.ajaxPrefilter to add CleanTalk data to jQuery ajax requests. + * Notes: + * - ajaxSetup.beforeSend is not used: a request can supply its own beforeSend and drop the default. + * - ajaxPrefilter runs for every jQuery ajax call after options are merged, so injection is guaranteed. + * - Form signs are checked on the request data/url at send time. + * - Any sign of the form HTML of the caller is insignificant in this process. + * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script + * will work independing if jQuery is loaded by CleanTalk or not + * @return {void} + */ + catchJqueryAjax() { + if ( typeof jQuery !== 'undefined' && typeof jQuery.ajaxPrefilter === 'function' ) { + jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { + const handler = new ApbctHandler(); + const sourceSign = handler.searchSignsForJQAjaxInjection(options, originalOptions); + if (sourceSign.found !== false) { + options.data = handler.injectCleantalkDataToJQAjax( + sourceSign, + handler.getJQAjaxPayloadForInject(options, originalOptions), + options, + ); + } + }); + } + } + + /** + * jQuery.param() on URLSearchParams/FormData can collapse options.data to "". + * Sign search already falls back to originalOptions; inject must use that payload too. + * @param {object} options + * @param {object=} originalOptions + * @return {*} + */ + getJQAjaxPayloadForInject(options, originalOptions) { + const current = options && options.data; + const original = originalOptions && originalOptions.data; + if ( this.jqAjaxPayloadWasCollapsed(current, original) ) { + return original; + } + return current; + } + + /** + * @param {*} current + * @param {*} original + * @return {boolean} + */ + jqAjaxPayloadWasCollapsed(current, original) { + if ( original === null || typeof original === 'undefined' ) { + return false; + } + if ( current === original ) { + return false; + } + const currentEmpty = current === '' || current === null || typeof current === 'undefined'; + if ( !currentEmpty ) { + return false; + } + if ( typeof original === 'string' ) { + return original !== ''; + } + return this.isJQAjaxFormData(original) || + this.isJQAjaxURLSearchParams(original) || + this.isJQAjaxPlainObjectOrArray(original); + } + + /** + * Normalize jQuery ajax data to a query string for sign search. + * Objects and serializeArray are read structurally so search never calls jQuery.param. + * Also reads known sign fields from the URL (IE11 FormData cannot be enumerated). + * @param {object} ajaxObject Ajax options object. + * @return {string} + */ + getJQAjaxDataAsString(ajaxObject) { + if ( !ajaxObject || typeof ajaxObject !== 'object' ) { + return ''; + } + let fromData = ''; + if ( typeof ajaxObject.data === 'string' ) { + fromData = ajaxObject.data; + } else if ( this.isJQAjaxPlainObjectOrArray(ajaxObject.data) ) { + fromData = this.getStructuredJQAjaxSignString(ajaxObject.data); + } else if ( this.isJQAjaxURLSearchParams(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } else if ( this.isJQAjaxFormData(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } + // Native IE11 FormData is write-only (no get/forEach/entries). Signs then come from the URL. + const fromUrl = this.collectKnownSignStringFromUrl(ajaxObject.url); + if ( fromData && fromUrl ) { + return fromData + '&' + fromUrl; + } + return fromData || fromUrl; + } + + /** + * Build a sign string from top-level fields without serializing the whole payload. + * @param {object|Array} data + * @return {string} + */ + getStructuredJQAjaxSignString(data) { + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return this.getSerializeArraySignString(data); + } + const parts = []; + const action = this.getPlainObjectSignField(data, 'action'); + if ( typeof action === 'string' && action !== '' ) { + parts.push('action=' + action); + } + const nonce = this.getPlainObjectSignField(data, 'ur_frontend_form_nonce'); + if ( nonce !== null ) { + parts.push('ur_frontend_form_nonce=' + nonce); + } + if ( this.plainObjectHasTwtCcSignup(data) ) { + parts.push('twt_cc_signup=1'); + } + return parts.join('&'); + } + + /** + * Read action/nonce from top-level, data[key], or nested data.key. + * @param {object} data + * @param {string} key + * @return {string|number|null} + */ + getPlainObjectSignField(data, key) { + if ( !data || typeof data !== 'object' ) { + return null; + } + if ( this.isJQAjaxScalarSignValue(data[key]) ) { + return data[key]; + } + const bracketKey = 'data[' + key + ']'; + if ( this.isJQAjaxScalarSignValue(data[bracketKey]) ) { + return data[bracketKey]; + } + if ( + data.data && + typeof data.data === 'object' && + Object.prototype.toString.call(data.data) !== '[object Array]' && + this.isJQAjaxScalarSignValue(data.data[key]) + ) { + return data.data[key]; + } + return null; + } + + /** + * @param {*} value + * @return {boolean} + */ + isJQAjaxScalarSignValue(value) { + return typeof value === 'string' || typeof value === 'number'; + } + + /** + * @param {object} data + * @param {number=} depth + * @return {boolean} + */ + plainObjectHasTwtCcSignup(data, depth) { + if ( !data || typeof data !== 'object' ) { + return false; + } + if ( typeof depth === 'undefined' ) { + depth = 0; + } + if ( depth > 2 ) { + return false; + } + for ( const key in data ) { + if ( !Object.prototype.hasOwnProperty.call(data, key) ) { + continue; + } + const normalizedKey = this.unwrapJQAjaxFormDataKey(key); + if ( normalizedKey === 'twt_cc_signup' || key.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + const value = data[key]; + if ( typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + if ( + value && + typeof value === 'object' && + Object.prototype.toString.call(value) !== '[object Array]' + ) { + if ( this.plainObjectHasTwtCcSignup(value, depth + 1) ) { + return true; + } + } + } + return false; + } + + /** + * @param {Array} entries + * @return {string} + */ + getSerializeArraySignString(entries) { + const parts = []; + for ( let i = 0; i < entries.length; i++ ) { + const entry = entries[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + continue; + } + const value = entry.value; + const normalizedKey = this.unwrapJQAjaxFormDataKey(entry.name); + if ( this.isJQAjaxKnownSignField(normalizedKey, value) ) { + parts.push(normalizedKey + '=' + value); + } + } + return parts.join('&'); + } + + /** + * True for serializeArray payloads, including an empty array. + * @param {Array} data + * @return {boolean} + */ + isJQAjaxSerializeArray(data) { + if ( Object.prototype.toString.call(data) !== '[object Array]' ) { + return false; + } + for ( let i = 0; i < data.length; i++ ) { + const entry = data[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + return false; + } + } + return true; + } + + /** + * Cross-realm URLSearchParams (instanceof fails across windows). + * @param {*} data + * @return {boolean} + */ + isJQAjaxURLSearchParams(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object URLSearchParams]' ) { + return true; + } + if ( tag === '[object FormData]' ) { + return false; + } + return typeof data.sort === 'function' && typeof data.get === 'function'; + } + + /** + * Cross-realm FormData, including common polyfills. + * @param {*} data + * @return {boolean} + */ + isJQAjaxFormData(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) || this.isJQAjaxURLSearchParams(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object FormData]' ) { + return true; + } + if ( tag === '[object Headers]' || typeof data.getSetCookie === 'function' ) { + return false; + } + return typeof data.forEach === 'function' || + typeof data.get === 'function' || + typeof data.entries === 'function'; + } + + /** + * Collect only known sign fields from FormData / URLSearchParams. + * Unwrap data[action] so later action=... checks match. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + collectKnownSignStringFromKeyValueBag(bag) { + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' ) { + return; + } + const valueAsString = String(value); + const normalizedKey = unwrapKey(key); + if ( + knownKeys[normalizedKey] || + valueAsString.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + valueAsString); + } + }); + if ( collected ) { + return parts.join('&'); + } + if ( typeof bag.get !== 'function' ) { + return ''; + } + const keysToProbe = [ + 'action', + 'ur_frontend_form_nonce', + 'twt_cc_signup', + ]; + const getParts = []; + for ( let i = 0; i < keysToProbe.length; i++ ) { + const key = keysToProbe[i]; + const value = this.getFormDataScalarValue(bag, [key, 'data[' + key + ']']); + if ( value !== null ) { + getParts.push(key + '=' + value); + } + } + return getParts.join('&'); + } + + /** + * Known sign fields from a request URL query. IE11-safe (no URLSearchParams). + * @param {string} url + * @return {string} + */ + collectKnownSignStringFromUrl(url) { + if ( typeof url !== 'string' || url === '' ) { + return ''; + } + const queryIndex = url.indexOf('?'); + if ( queryIndex === -1 || queryIndex === url.length - 1 ) { + return ''; + } + const hashIndex = url.indexOf('#', queryIndex); + const query = hashIndex === -1 ? + url.slice(queryIndex + 1) : + url.slice(queryIndex + 1, hashIndex); + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const pairs = query.split('&'); + for ( let i = 0; i < pairs.length; i++ ) { + const pair = pairs[i]; + if ( !pair ) { + continue; + } + const eq = pair.indexOf('='); + let rawKey = eq === -1 ? pair : pair.slice(0, eq); + let rawValue = eq === -1 ? '' : pair.slice(eq + 1); + try { + rawKey = decodeURIComponent(rawKey.replace(/\+/g, ' ')); + rawValue = decodeURIComponent(rawValue.replace(/\+/g, ' ')); + } catch (e) { + continue; + } + const normalizedKey = unwrapKey(rawKey); + if ( + knownKeys[normalizedKey] || + rawValue.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + rawValue); + } + } + return parts.join('&'); + } + + /** + * Walk FormData/URLSearchParams via forEach, then entries() for polyfills that only have an iterator. + * @param {FormData|URLSearchParams} bag + * @param {Function} callback + * @return {boolean} + */ + forEachJQAjaxKeyValueBag(bag, callback) { + if ( typeof bag.forEach === 'function' ) { + try { + bag.forEach(callback); + return true; + } catch (e) { + // Fall through to entries(). + } + } + if ( typeof bag.entries !== 'function' ) { + return false; + } + try { + const iterator = bag.entries(); + if ( !iterator || typeof iterator.next !== 'function' ) { + return false; + } + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + callback(pair[1], pair[0]); + } + step = iterator.next(); + } + return true; + } catch (e) { + return false; + } + } + + /** + * @return {Object} + */ + getJQAjaxKnownSignKeys() { + const knownKeys = Object.create(null); + knownKeys.action = true; + knownKeys.ur_frontend_form_nonce = true; + knownKeys.twt_cc_signup = true; + return knownKeys; + } + + /** + * @param {string} normalizedKey + * @param {*} value + * @return {boolean} + */ + isJQAjaxKnownSignField(normalizedKey, value) { + if ( + normalizedKey === 'action' || + normalizedKey === 'ur_frontend_form_nonce' || + normalizedKey === 'twt_cc_signup' || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + return true; + } + return typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1; + } + + /** + * Treat data[action] as action for WP-style payloads. + * @param {string} key + * @return {string} + */ + unwrapJQAjaxFormDataKey(key) { + if ( typeof key !== 'string' ) { + return ''; + } + if ( key.length > 6 && key.indexOf('data[') === 0 && key.charAt(key.length - 1) === ']' ) { + return key.slice(5, -1); + } + return key; + } + + /** + * @param {FormData} formData + * @param {Array.} keys + * @return {string|number|null} + */ + getFormDataScalarValue(formData, keys) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && (typeof value === 'string' || typeof value === 'number') ) { + return value; + } + } + return null; + } + + /** + * True for arrays and plain objects that jQuery.param can serialize safely. + * @param {*} data + * @return {boolean} + */ + isJQAjaxPlainObjectOrArray(data) { + if ( data === null || typeof data !== 'object' ) { + return false; + } + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return true; + } + if ( typeof jQuery !== 'undefined' && typeof jQuery.isPlainObject === 'function' ) { + return jQuery.isPlainObject(data); + } + const proto = Object.getPrototypeOf(data); + return proto === Object.prototype || proto === null; + } + + /** + * Search for sign within AJAX data to do inject CleanTalk data. + * @param {object} ajaxObject Ajax object. + * @param {object=} originalOptions Original jQuery ajax options before merge. + * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + */ + searchSignsForJQAjaxInjection(ajaxObject, originalOptions) { + let sourceSign = { + 'found': false, + 'keepUnwrapped': false, + 'attachVisibleFieldsData': false, + }; + let dataString = this.getJQAjaxDataAsString(ajaxObject); + if ( !dataString && originalOptions && originalOptions !== ajaxObject ) { + dataString = this.getJQAjaxDataAsString(originalOptions); + } + + if ( dataString.indexOf('action=fl_builder_subscribe_form_submit') !== -1 ) { + sourceSign.found = 'fl_builder_subscribe_form_submit'; + } + if ( dataString.indexOf('twt_cc_signup') !== -1 ) { + sourceSign.found = 'twt_cc_signup'; + } + if ( dataString.indexOf('action=mailpoet') !== -1 ) { + sourceSign.found = 'action=mailpoet'; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=user_registration') !== -1 && + dataString.indexOf('ur_frontend_form_nonce') !== -1 + ) { + sourceSign.found = 'action=user_registration'; + } + if ( dataString.indexOf('action=happyforms_message') !== -1 ) { + sourceSign.found = 'action=happyforms_message'; + } + if ( dataString.indexOf('action=new_activity_comment') !== -1 ) { + sourceSign.found = 'action=new_activity_comment'; + } + if ( dataString.indexOf('action=wwlc_create_user') !== -1 ) { + sourceSign.found = 'action=wwlc_create_user'; + } + if ( dataString.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 ) { + sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=drplus_signup') !== -1 ) { + sourceSign.found = 'action=drplus_signup'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=bt_cc') !== -1 ) { + sourceSign.found = 'action=bt_cc'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=wpr_form_builder_email') !== -1 ) { + sourceSign.found = 'action=wpr_form_builder_email'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=nf_ajax_submit') !== -1 ) { + sourceSign.found = 'action=nf_ajax_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=uael_register_user') !== -1 && + ctPublic.data__cookies_type === 'none' + ) { + sourceSign.found = 'action=uael_register_user'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=SQBSubmitQuizAjax') !== -1 ) { + sourceSign.found = 'action=SQBSubmitQuizAjax'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=user_registration_user_form_submit') !== -1 ) { + sourceSign.found = 'action=user_registration_user_form_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=bloom_subscribe') !== -1 ) { + sourceSign.found = 'action=bloom_subscribe'; + sourceSign.keepUnwrapped = true; + } + if ( + this.isJQAjaxFormData(ajaxObject.data) && + typeof ajaxObject.data.get === 'function' && + ajaxObject.data.get('action') === 'pafe_ajax_form_builder' + ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } else if ( dataString.indexOf('action=pafe_ajax_form_builder') !== -1 ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } + + // woocommerce add to cart is based on URL + if ( typeof ajaxObject.url === 'string' && ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1 ) { + sourceSign.found = 'wc-ajax=add_to_cart'; + // GET/HEAD: PHP reads Get::get('ct_bot_detector_event_token'), not data[...]. + if ( this.isJQAjaxNoContentMethod(ajaxObject) ) { + sourceSign.keepUnwrapped = true; + } + } + + return sourceSign; + } + + /** + * Inject CleanTalk data into jQuery ajax payload of any supported type. + * @param {object} sourceSign + * @param {*} ajaxData + * @param {object=} ajaxOptions jQuery ajax options (traditional, processData, contentType). + * Keep URLSearchParams/objects when processData or contentType is false. + * URLSearchParams must also disable processData, or jQuery.param() later yields "". + * GET/HEAD never keep the original type: jQuery only puts string data on the URL. + * @return {*} + */ + injectCleantalkDataToJQAjax(sourceSign, ajaxData, ajaxOptions) { + const traditional = ajaxOptions && ajaxOptions.traditional; + const keepOriginalType = !this.isJQAjaxNoContentMethod(ajaxOptions) && !!(ajaxOptions && ( + ajaxOptions.processData === false || + ajaxOptions.contentType === false + )); + + if ( ajaxData === null || typeof ajaxData === 'undefined' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ''); + } + if ( typeof ajaxData === 'string' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData); + } + if ( this.isJQAjaxPlainObjectOrArray(ajaxData) ) { + if ( keepOriginalType ) { + if ( Object.prototype.toString.call(ajaxData) === '[object Array]' ) { + if ( this.isJQAjaxSerializeArray(ajaxData) ) { + return this.injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData); + } + return ajaxData; + } + return this.injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData); + } + try { + if ( typeof jQuery !== 'undefined' && typeof jQuery.param === 'function' ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + jQuery.param(ajaxData, traditional), + ); + } + } catch (e) { + return ajaxData; + } + return ajaxData; + } + if ( this.isJQAjaxURLSearchParams(ajaxData) ) { + if ( keepOriginalType ) { + this.preserveJQAjaxURLSearchParamsOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxKeyValue( + sourceSign, + this.cloneURLSearchParams(ajaxData), + ); + } + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData.toString()); + } + if ( this.isJQAjaxFormData(ajaxData) ) { + if ( this.isJQAjaxNoContentMethod(ajaxOptions) ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + this.serializeJQAjaxKeyValueBag(ajaxData), + ); + } + this.preserveJQAjaxFormDataOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxFormData( + sourceSign, + this.cloneFormData(ajaxData), + ); + } + return ajaxData; + } + + /** + * GET/HEAD have no body. Missing type is GET (jQuery default). + * @param {object=} ajaxOptions + * @return {boolean} + */ + isJQAjaxNoContentMethod(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return false; + } + const type = ajaxOptions.type || ajaxOptions.method; + if ( typeof type !== 'string' || type === '' ) { + return true; + } + const method = type.toUpperCase(); + return method === 'GET' || method === 'HEAD'; + } + + /** + * Collect CleanTalk fields to append to a key/value payload. + * @param {object} sourceSign + * @return {Array.>} + */ + getCleantalkJQAjaxFieldPairs(sourceSign) { + const pairs = []; + const wrapKey = function(key) { + return sourceSign.keepUnwrapped ? key : 'data[' + key + ']'; + }; + + if ( + +ctPublic.bot_detector_enabled && + apbctLocalStorage.get('bot_detector_event_token') + ) { + const token = this.toolGetEventToken(); + if ( token ) { + pairs.push([wrapKey('ct_bot_detector_event_token'), token]); + } + } else { + const noCookieData = getNoCookieData(); + if ( noCookieData ) { + pairs.push([wrapKey('ct_no_cookie_hidden_field'), noCookieData]); + } + } + + const browserState = apbctGetBrowserStatePair(); + if ( browserState ) { + const browserStateKey = sourceSign.keepUnwrapped ? + browserState.key : + 'data[' + browserState.key + ']'; + pairs.push([browserStateKey, browserState.value]); + } + + return pairs; + } + + /** + * jQuery.param(FormData) after the prefilter yields "". Keep the body as FormData. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxFormDataOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + ajaxOptions.contentType = false; + } + + /** + * jQuery.param(URLSearchParams) after the prefilter yields "". Keep the body as URLSearchParams. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxURLSearchParamsOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + } + + /** + * Read a FormData field via get(), forEach(), or entries(). + * Native IE11 FormData is write-only and cannot be read. + * @param {FormData} formData + * @param {Array.} keys + * @return {*} + */ + getFormDataField(formData, keys) { + if ( typeof formData.get === 'function' ) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && typeof value !== 'undefined' ) { + return value; + } + } + } + if ( typeof formData.forEach === 'function' ) { + let found = null; + formData.forEach(function(value, key) { + if ( found !== null ) { + return; + } + for ( let i = 0; i < keys.length; i++ ) { + if ( key === keys[i] ) { + found = value; + return; } } - - // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === - if ( - +ctPublic.settings__forms__wc_add_to_cart && - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/batch') && - typeof args[1].body === 'string' - ) { - try { - const batchPayload = JSON.parse(args[1].body); - if (batchPayload.requests && Array.isArray(batchPayload.requests)) { - const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); - for (const req of batchPayload.requests) { - const isAddItem = req.path === '/wc/store/v1/cart/add-item'; - if (isAddItem && req.body && fieldPair && fieldPair.key) { - req.body[fieldPair.key] = fieldPair.value; + }); + if ( found !== null ) { + return found; + } + } + if ( typeof formData.entries === 'function' ) { + try { + const iterator = formData.entries(); + if ( iterator && typeof iterator.next === 'function' ) { + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + for ( let i = 0; i < keys.length; i++ ) { + if ( pair[0] === keys[i] ) { + return pair[1]; } } - args[1].body = JSON.stringify(batchPayload); } - } catch (e) { - // Continue even if error + step = iterator.next(); } } - - // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === - preventOriginalFetch = await processIframeCommonFetch(url, args); - - // Return original fetch result if not prevented - if (!preventOriginalFetch) { - return originalFetch.apply(this, args); - } - } catch (error) { - // In case of any error in our interceptor, call original fetch - return originalFetch.apply(this, args); + } catch (e) { + return null; } - }; + } + return null; } /** - * Prepare jQuery.ajaxSetup to add nocookie data to the jQuery ajax request. - * Notes: - * - Do it just once, the ajaxSetup.beforeSend will be overwritten for any calls. - * - Signs of forms need to be caught will be checked during ajaxSetup.settings.data process on send. - * - Any sign of the form HTML of the caller is insignificant in this process. - * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script - * will work independing if jQuery is loaded by CleanTalk or not - * @return {void} + * Clone URLSearchParams so the caller's instance is not mutated. + * @param {URLSearchParams} params + * @return {URLSearchParams} */ - catchJqueryAjax() { - if ( typeof jQuery !== 'undefined') { - // this code run on base ajax rules - so do not work due scripts use it's own ajax object injections - if ( typeof jQuery.ajaxSetup === 'function' ) { - jQuery.ajaxSetup({ - beforeSend: function(xhr, settings) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(settings, 'ajaxSetup'); - if (sourceSign.found !== false) { - settings.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, settings.data); - } - }, - }); + cloneURLSearchParams(params) { + const serialized = typeof params.toString === 'function' ? params.toString() : ''; + if ( typeof params.constructor === 'function' && params.constructor !== Object ) { + try { + return new params.constructor(serialized); + } catch (e) { + // Fall through to the current-window constructor. } - // this code run on ANY ajax on ANY script queue status - // todo Probably move all ajaxSetup actions to ajaxPrefilter - if ( typeof jQuery.ajaxPrefilter === 'function' ) { - jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(options, 'ajaxPrefilter'); - if (sourceSign.found !== false) { - if (typeof options.data === 'string') { - options.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, options.data); - } - if ( - typeof options.data === 'object' && - typeof options.data.append === 'function' - ) { - options.data = handler.injectCleantalkDataToJQAjaxFormData(sourceSign, options.data); - } - } - }); + } + if ( typeof URLSearchParams === 'function' ) { + try { + return new URLSearchParams(serialized); + } catch (e) { + return params; } } + return params; } /** - * Search for sign within AJAX data to do inject CleanTalk data. - * @param {object} ajaxObject Ajax object. - * @param {string} catchOn Function should be catched on. - * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + * Clone FormData when it can be enumerated (forEach or entries); otherwise reuse. + * @param {FormData} formData + * @return {FormData} */ - searchSignsForJQAjaxInjection(ajaxObject, catchOn = 'ajaxSetup') { - let sourceSign = { - 'found': false, - 'keepUnwrapped': false, - 'attachVisibleFieldsData': false, - }; - // on ajaxSetup - if (catchOn === 'ajaxSetup') { - // settings data is string (important!) - if ( typeof ajaxObject.data === 'string' ) { - if ( - ajaxObject.data.indexOf('action=fl_builder_subscribe_form_submit') !== -1 - ) { - sourceSign.found = 'fl_builder_subscribe_form_submit'; - } - if ( - ajaxObject.data.indexOf('twt_cc_signup') !== -1 - ) { - sourceSign.found = 'twt_cc_signup'; - } - if ( - ajaxObject.data.indexOf('action=mailpoet') !== -1 - ) { - sourceSign.found = 'action=mailpoet'; - sourceSign.attachVisibleFieldsData = true; - } - - if ( - ajaxObject.data.indexOf('action=user_registration') !== -1 && - ajaxObject.data.indexOf('ur_frontend_form_nonce') !== -1 - ) { - sourceSign.found = 'action=user_registration'; - } - - if (ajaxObject.data.indexOf('action=happyforms_message') !== -1) { - sourceSign.found = 'action=happyforms_message'; - } + cloneFormData(formData) { + try { + const clone = new FormData(); + const copied = this.forEachJQAjaxKeyValueBag(formData, function(value, key) { + clone.append(key, value); + }); + if ( copied ) { + return clone; + } + } catch (e) { + return formData; + } + return formData; + } - if ( - ajaxObject.data.indexOf('action=new_activity_comment') !== -1 - ) { - sourceSign.found = 'action=new_activity_comment'; - } - if ( - ajaxObject.data.indexOf('action=wwlc_create_user') !== -1 - ) { - sourceSign.found = 'action=wwlc_create_user'; - } - if ( - ajaxObject.data.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 - ) { - sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=drplus_signup') !== -1 - ) { - sourceSign.found = 'action=drplus_signup'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=bt_cc') !== -1 - ) { - sourceSign.found = 'action=bt_cc'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=wpr_form_builder_email') !== -1 - ) { - sourceSign.found = 'action=wpr_form_builder_email'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=nf_ajax_submit') !== -1 - ) { - sourceSign.found = 'action=nf_ajax_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=uael_register_user') !== -1 && - ctPublic.data__cookies_type === 'none' - ) { - sourceSign.found = 'action=uael_register_user'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=SQBSubmitQuizAjax') !== -1 - ) { - sourceSign.found = 'action=SQBSubmitQuizAjax'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=user_registration_user_form_submit') !== -1 - ) { - sourceSign.found = 'action=user_registration_user_form_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } + /** + * Form-urlencoded string from FormData/URLSearchParams. Skip File/Blob values. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + serializeJQAjaxKeyValueBag(bag) { + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { + return; } - // wooocommerce add to cart is based on URL - if ( typeof ajaxObject.url === 'string' ) { - if (ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1) { - sourceSign.found = 'wc-ajax=add_to_cart'; + parts.push(encodeURIComponent(String(key)) + '=' + encodeURIComponent(String(value))); + }); + if ( collected ) { + return parts.join('&'); + } + return ''; + } + + /** + * Inject CleanTalk fields into URLSearchParams without changing the payload type. + * @param {object} sourceSign + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + injectCleantalkDataToJQAjaxKeyValue(sourceSign, params) { + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + params.append(pairs[i][0], pairs[i][1]); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( extractor ) { + const extracted = extractor.extract(params.toString()); + if ( typeof extracted === 'string' ) { + params.append('apbct_visible_fields', extracted); } } } + return params; + } - // on ajaxPrefilter - if (catchOn === 'ajaxPrefilter') { - if (typeof ajaxObject.data === 'string') { - if (ajaxObject.data.indexOf('action=bloom_subscribe') !== -1) { - sourceSign.found = 'action=bloom_subscribe'; - sourceSign.keepUnwrapped = true; + /** + * Inject CleanTalk fields into a jQuery serializeArray payload. + * @param {object} sourceSign + * @param {Array} ajaxData + * @return {Array} + */ + injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData) { + const result = ajaxData.slice(); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result.push({ + name: pairs[i][0], + value: pairs[i][1], + }); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' + ) { + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.push({ + name: 'apbct_visible_fields', + value: extracted, + }); } } + } + return result; + } + /** + * Inject CleanTalk fields into a plain object without changing the payload type. + * @param {object} sourceSign + * @param {object} ajaxData + * @return {object} + */ + injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData) { + const result = typeof jQuery !== 'undefined' && typeof jQuery.extend === 'function' ? + jQuery.extend({}, ajaxData) : + this.clonePlainObject(ajaxData); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result[pairs[i][0]] = pairs[i][1]; + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); if ( - typeof ajaxObject.data === 'object' && - ajaxObject.data !== null && - typeof ajaxObject.data.get === 'function' + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' ) { - if (ajaxObject.data.get('action') === 'pafe_ajax_form_builder') { - sourceSign.found = 'action=pafe_ajax_form_builder'; - sourceSign.keepUnwrapped = true; + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.apbct_visible_fields = extracted; } } } + return result; + } - return sourceSign; + /** + * IE11-safe shallow copy of a plain object. + * @param {object} ajaxData + * @return {object} + */ + clonePlainObject(ajaxData) { + const result = {}; + for ( const key in ajaxData ) { + if ( Object.prototype.hasOwnProperty.call(ajaxData, key) ) { + result[key] = ajaxData[key]; + } + } + return result; } /** @@ -4021,8 +4881,7 @@ class ApbctHandler { injectCleantalkDataToJQAjaxFormData(sourceSign, ajaxDataFormData) { if ( typeof sourceSign !== 'object' || - typeof ajaxDataFormData !== 'object' || - !(ajaxDataFormData instanceof FormData) + !this.isJQAjaxFormData(ajaxDataFormData) ) { return ajaxDataFormData; } @@ -4053,6 +4912,16 @@ class ApbctHandler { } } + // Bot detector browser state + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append(browserState.key, browserState.value); + } else { + ajaxDataFormData.append('data[' + browserState.key + ']', browserState.value); + } + } + // Visible fields if (sourceSign.attachVisibleFieldsData) { let visibleFieldsSearchResult = false; @@ -4060,13 +4929,10 @@ class ApbctHandler { if (extractor) { // Try to find form_id in FormData to find form container and // collect visible fields only inside it - let formId = null; - for (let pair of ajaxDataFormData.entries()) { - if (pair[0] === 'form_id' || pair[0] === 'data[form_id]') { - formId = pair[1]; - break; - } - } + const formId = this.getFormDataField( + ajaxDataFormData, + ['form_id', 'data[form_id]'], + ); let container = null; if (formId && typeof formId === 'string') { // Sanitize formId to prevent selector injection @@ -4111,6 +4977,15 @@ class ApbctHandler { let eventToken = ''; let noCookieData = ''; let visibleFieldsString = ''; + let browserStateString = ''; + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + const browserStateKey = sourceSign.keepUnwrapped ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; + browserStateString = browserStateKey + '=' + encodeURIComponent(browserState.value) + '&'; + } if ( +ctPublic.bot_detector_enabled && @@ -4127,9 +5002,9 @@ class ApbctHandler { } else { noCookieData = getNoCookieData(); if (sourceSign.keepUnwrapped) { - noCookieData = 'ct_no_cookie_hidden_field=' + noCookieData + '&'; + noCookieData = 'ct_no_cookie_hidden_field=' + encodeURIComponent(noCookieData) + '&'; } else { - noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + noCookieData + '&'; + noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + encodeURIComponent(noCookieData) + '&'; } } @@ -4152,7 +5027,7 @@ class ApbctHandler { } } - return noCookieData + eventToken + visibleFieldsString + ajaxDataString; + return noCookieData + eventToken + browserStateString + visibleFieldsString + ajaxDataString; } /** @@ -6473,67 +7348,126 @@ function ctCheckInternalIsExcludedForm(action) { }); } -let botDetectorLogLastUpdate = 0; -let botDetectorLogEventTypesCollected = []; - -// bot_detector frontend_data log alt session saving cron -if ( - ctPublicFunctions.hasOwnProperty('bot_detector_enabled') && - +ctPublicFunctions.bot_detector_enabled && - ctPublicFunctions.hasOwnProperty('data__frontend_data_log_enabled') && - ctPublicFunctions.data__frontend_data_log_enabled == 1 -) { - sendBotDetectorLogToAltSessions(1000); -} - /** - * Send BotDetector logs data to alternative sessions. - * If log_last_update has changed and log contains new event types, the log will be sent to the alternative sessions. - * @param {int} cronStartTimeout delay before cron start - * @param {int} interval check fires on interval + * Bot detector browser state. + * + * The state is passed to the site backend with the current JS->PHP transport and goes + * to the moderate request as sender_info.bot_detector_frontend_data_log. */ -function sendBotDetectorLogToAltSessions(cronStartTimeout = 3000, interval = 1000) { - setTimeout(function() { - setInterval(function() { - const currentLog = apbctLocalStorage.get('ct_bot_detector_frontend_data_log'); - if (needsSaveLogToAltSessions(currentLog)) { - botDetectorLogLastUpdate = currentLog.log_last_update; - // the log will be taken from javascriptclientdata - ctSetAlternativeCookie([], {forceAltCookies: true}); - } - }, interval); - }, cronStartTimeout); -} +class ApbctBrowserState { + static STATE_KEY = 'apbct_browser_state'; + static LOG_KEY = 'ct_bot_detector_frontend_data_log'; + static SCRIPT_SIGNS = { + botd_wrapper_loaded: 'ct-bot-detector-wrapper', + botd_logic_loaded: 'ct-bot-detector.min', + }; + /** + * This LS key is set on bot-detector side + * @type {string} + */ + static TRANSPORT_ENABLED_SIGN_KEY = 'bot_detector_log_transport_enabled'; + static botdWrapperLoaded = 0; + static botdLogicLoaded = 0; -/** - * Check if the log needs to be saved to the alt sessions. If the log has new event types, it will be saved. - * @param {object} currentLog - * @return {boolean} - */ -function needsSaveLogToAltSessions(currentLog) { - if ( - currentLog && currentLog.hasOwnProperty('log_last_update') && - botDetectorLogLastUpdate !== currentLog.log_last_update - ) { - try { - for (let i = 0; i < currentLog.records.length; i++) { - const currentType = currentLog.records[i].frontend_data.js_event; - // check if this event type was already collected - if (currentType !== undefined && botDetectorLogEventTypesCollected.includes(currentType)) { - continue; + /** + * Get the current browser state as a JSON string ready to be transferred. + * @return {string} Empty string if the bot detector is disabled or on any collecting error. + */ + static getFrontendDataLog() { + const prefix = (typeof ctPublicFunctions !== 'undefined' && ctPublicFunctions.cookiePrefix) ? + ctPublicFunctions.cookiePrefix : + ''; + const logKey = prefix + ApbctBrowserState.LOG_KEY; + const noPrefixLogKey = ApbctBrowserState.LOG_KEY; + + if (typeof apbctLocalStorage !== 'undefined' && apbctLocalStorage.get) { + const logObject = apbctLocalStorage.get(logKey) || apbctLocalStorage.get(noPrefixLogKey) || null; + if (logObject && typeof logObject === 'string') { + try { + return JSON.parse(logObject); + } catch (e) { + return ''; } - // add new event type to collection, this type will be sent to the alt sessions further - botDetectorLogEventTypesCollected.push(currentType); - return true; } + return logObject; + } + + let rawLog = localStorage.getItem(logKey); + if (!rawLog) { + rawLog = localStorage.getItem(noPrefixLogKey) || null; + } + + try { + return typeof rawLog === 'string' ? JSON.parse(rawLog) : rawLog; } catch (e) { - console.log('APBCT: bot detector log collection error: ' . e.toString()); + return ''; } } - return false; -} + /** + * + * @return {object} + */ + static asDTO() { + return { + botd_logic_loaded: ApbctBrowserState.botdLogicLoaded, + botd_wrapper_loaded: ApbctBrowserState.botdWrapperLoaded, + frontend_data_log: '', + transport_enabled: 1, + }; + } + + /** + * Look for the bot detector scripts in the page DOM. + * @return {boolean} True if both scripts are found. + */ + static detectScripts() { + if (ApbctBrowserState.botdWrapperLoaded && ApbctBrowserState.botdLogicLoaded) { + return true; + } + + const scripts = document.getElementsByTagName('script'); + + for (let i = 0; i < scripts.length; i++) { + const src = scripts[i].getAttribute('src'); + if (!src) { + continue; + } + if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_wrapper_loaded) !== -1) { + ApbctBrowserState.botdWrapperLoaded = 1; + } else if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_logic_loaded) !== -1) { + ApbctBrowserState.botdLogicLoaded = 1; + } + } + + // The bot detector logic sets this flag on its own start + return !!ApbctBrowserState.botdWrapperLoaded && !!ApbctBrowserState.botdLogicLoaded; + } +} +/** + * Get the browser state as a key/value pair to attach it to an intercepted request. + * @return {{key: string, value: string}|false} False if there is nothing to attach. + */ +function apbctGetBrowserStatePair() { // eslint-disable-line no-unused-vars + try { + ApbctBrowserState.detectScripts(); + let state = ApbctBrowserState.asDTO(); + if ( ApbctBrowserState.botdLogicLoaded ) { + const transportEnabled = localStorage.getItem(ApbctBrowserState.TRANSPORT_ENABLED_SIGN_KEY) === '1'; + if (transportEnabled) { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } else { + state.transport_enabled = 0; + } + } else { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } + return {key: ApbctBrowserState.STATE_KEY, value: JSON.stringify(state)}; + } catch (e) { + return false; + } +} let ctCheckedEmails = {}; let ctCheckedEmailsExist = {}; diff --git a/js/prebuild/apbct-public-bundle_full-protection_gathering.js b/js/prebuild/apbct-public-bundle_full-protection_gathering.js index 98230542b..70ab6bb1b 100644 --- a/js/prebuild/apbct-public-bundle_full-protection_gathering.js +++ b/js/prebuild/apbct-public-bundle_full-protection_gathering.js @@ -2253,7 +2253,7 @@ function ctSetCookie( cookies, value, expires='') { let listOfCookieNamesToForceAlt = [ 'ct_sfw_pass_key', 'ct_sfw_passed', - 'wordpress_apbct_antibot', + 'apbct_antibot', 'apbct_anticrawler_passed', 'apbct_bot_detector_exist', 'apbct_antiflood_passed', @@ -2642,6 +2642,15 @@ function getNoCookieData() { // eslint-disable-line no-unused-vars let noCookieDataLocal = apbctLocalStorage.getCleanTalkData(); let noCookieDataSession = apbctSessionStorage.getCleanTalkData(); let noCookieData = {...noCookieDataLocal, ...noCookieDataSession}; + + // Bot detector browser state is transferred with the hidden field on the NoCookie mode + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + noCookieData[browserState.key] = browserState.value; + } + } + noCookieData = JSON.stringify(noCookieData); return '_ct_no_cookie_data_' + btoa(unescape(encodeURIComponent(noCookieData))); @@ -2669,7 +2678,21 @@ function getCleanTalkStorageDataArray() { // eslint-disable-line no-unused-vars noCookieDataFromUserActivity = {collecting_user_activity_data: collectingUserActivityData}; } - return {...noCookieDataLocal, ...noCookieDataSession, ...noCookieDataTypo, ...noCookieDataFromUserActivity}; + let browserStateData = {}; + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + browserStateData[browserState.key] = browserState.value; + } + } + + return { + ...noCookieDataLocal, + ...noCookieDataSession, + ...noCookieDataTypo, + ...noCookieDataFromUserActivity, + ...browserStateData, + }; } /** @@ -3314,6 +3337,9 @@ class ApbctHandler { const eventTokenKey = useUnwrappedCleantalkKeys ? 'ct_bot_detector_event_token' : 'data%5Bct_bot_detector_event_token%5D'; + const browserStateKey = useUnwrappedCleantalkKeys ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; if (!( +ctPublic.bot_detector_enabled && @@ -3338,6 +3364,12 @@ class ApbctHandler { } } + const browserState = apbctGetBrowserStatePair(); + if (browserState && body.indexOf('apbct_browser_state') === -1) { + addidionalCleantalkData += '&' + browserStateKey + '=' + + encodeURIComponent(browserState.value); + } + body += addidionalCleantalkData; } @@ -3354,6 +3386,11 @@ class ApbctHandler { body.append('ct_bot_detector_event_token', eventToken); } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState && !body.has(browserState.key)) { + body.append(browserState.key, browserState.value); + } } if (isNeedToAddCleantalkDataCheckJsonData) { @@ -3391,6 +3428,22 @@ class ApbctHandler { } } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + try { + const bodyObj = JSON.parse(body); + if ( + bodyObj && typeof bodyObj === 'object' && + !Object.prototype.hasOwnProperty.call(bodyObj, browserState.key) + ) { + bodyObj[browserState.key] = browserState.value; + body = JSON.stringify(bodyObj); + } + } catch (e) { + // body is not JSON — leave as is + } + } } return originalSend.apply(this, [body]); @@ -3448,6 +3501,11 @@ class ApbctHandler { } else { args[1].body.append('ct_no_cookie_hidden_field', getNoCookieData()); } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + args[1].body.append(browserState.key, browserState.value); + } } } } catch (e) { @@ -3504,6 +3562,22 @@ class ApbctHandler { * @return {string|FormData} Modified body. */ const attachFieldsToBody = function(body, fieldPair = false) { + const fieldPairs = [fieldPair, apbctGetBrowserStatePair()]; + + for (const pair of fieldPairs) { + body = attachFieldPairToBody(body, pair); + } + + return body; + }; + + /** + * Attach a single key/value pair to fetch request body + * @param {string|FormData} body Fetch request data body. + * @param {object|bool} fieldPair Key value to inject. + * @return {string|FormData} Modified body. + */ + const attachFieldPairToBody = function(body, fieldPair = false) { if (fieldPair) { if (body instanceof FormData || typeof body.append === 'function') { body.append(fieldPair.key, fieldPair.value); @@ -3761,255 +3835,1041 @@ class ApbctHandler { // Continue even if error } } - - // === WooCommerce add to cart (direct add-item URL) === - if ( - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/cart/add-item') - ) { - try { - if (+ctPublic.settings__forms__wc_add_to_cart) { - args[1].body = attachFieldsToBody( - args[1].body, - selectFieldsData(+ctPublic.bot_detector_enabled), - ); - } - } catch (e) { - // Continue even if error + + // === WooCommerce add to cart (direct add-item URL) === + if ( + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/cart/add-item') + ) { + try { + if (+ctPublic.settings__forms__wc_add_to_cart) { + args[1].body = attachFieldsToBody( + args[1].body, + selectFieldsData(+ctPublic.bot_detector_enabled), + ); + } + } catch (e) { + // Continue even if error + } + } + + // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === + if ( + +ctPublic.settings__forms__wc_add_to_cart && + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/batch') && + typeof args[1].body === 'string' + ) { + try { + const batchPayload = JSON.parse(args[1].body); + if (batchPayload.requests && Array.isArray(batchPayload.requests)) { + const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); + const browserState = apbctGetBrowserStatePair(); + for (const req of batchPayload.requests) { + const isAddItem = req.path === '/wc/store/v1/cart/add-item'; + if (isAddItem && req.body && fieldPair && fieldPair.key) { + req.body[fieldPair.key] = fieldPair.value; + } + if (isAddItem && req.body && browserState) { + req.body[browserState.key] = browserState.value; + } + } + args[1].body = JSON.stringify(batchPayload); + } + } catch (e) { + // Continue even if error + } + } + + // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === + preventOriginalFetch = await processIframeCommonFetch(url, args); + + // Return original fetch result if not prevented + if (!preventOriginalFetch) { + return originalFetch.apply(this, args); + } + } catch (error) { + // In case of any error in our interceptor, call original fetch + return originalFetch.apply(this, args); + } + }; + } + + /** + * Prepare jQuery.ajaxPrefilter to add CleanTalk data to jQuery ajax requests. + * Notes: + * - ajaxSetup.beforeSend is not used: a request can supply its own beforeSend and drop the default. + * - ajaxPrefilter runs for every jQuery ajax call after options are merged, so injection is guaranteed. + * - Form signs are checked on the request data/url at send time. + * - Any sign of the form HTML of the caller is insignificant in this process. + * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script + * will work independing if jQuery is loaded by CleanTalk or not + * @return {void} + */ + catchJqueryAjax() { + if ( typeof jQuery !== 'undefined' && typeof jQuery.ajaxPrefilter === 'function' ) { + jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { + const handler = new ApbctHandler(); + const sourceSign = handler.searchSignsForJQAjaxInjection(options, originalOptions); + if (sourceSign.found !== false) { + options.data = handler.injectCleantalkDataToJQAjax( + sourceSign, + handler.getJQAjaxPayloadForInject(options, originalOptions), + options, + ); + } + }); + } + } + + /** + * jQuery.param() on URLSearchParams/FormData can collapse options.data to "". + * Sign search already falls back to originalOptions; inject must use that payload too. + * @param {object} options + * @param {object=} originalOptions + * @return {*} + */ + getJQAjaxPayloadForInject(options, originalOptions) { + const current = options && options.data; + const original = originalOptions && originalOptions.data; + if ( this.jqAjaxPayloadWasCollapsed(current, original) ) { + return original; + } + return current; + } + + /** + * @param {*} current + * @param {*} original + * @return {boolean} + */ + jqAjaxPayloadWasCollapsed(current, original) { + if ( original === null || typeof original === 'undefined' ) { + return false; + } + if ( current === original ) { + return false; + } + const currentEmpty = current === '' || current === null || typeof current === 'undefined'; + if ( !currentEmpty ) { + return false; + } + if ( typeof original === 'string' ) { + return original !== ''; + } + return this.isJQAjaxFormData(original) || + this.isJQAjaxURLSearchParams(original) || + this.isJQAjaxPlainObjectOrArray(original); + } + + /** + * Normalize jQuery ajax data to a query string for sign search. + * Objects and serializeArray are read structurally so search never calls jQuery.param. + * Also reads known sign fields from the URL (IE11 FormData cannot be enumerated). + * @param {object} ajaxObject Ajax options object. + * @return {string} + */ + getJQAjaxDataAsString(ajaxObject) { + if ( !ajaxObject || typeof ajaxObject !== 'object' ) { + return ''; + } + let fromData = ''; + if ( typeof ajaxObject.data === 'string' ) { + fromData = ajaxObject.data; + } else if ( this.isJQAjaxPlainObjectOrArray(ajaxObject.data) ) { + fromData = this.getStructuredJQAjaxSignString(ajaxObject.data); + } else if ( this.isJQAjaxURLSearchParams(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } else if ( this.isJQAjaxFormData(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } + // Native IE11 FormData is write-only (no get/forEach/entries). Signs then come from the URL. + const fromUrl = this.collectKnownSignStringFromUrl(ajaxObject.url); + if ( fromData && fromUrl ) { + return fromData + '&' + fromUrl; + } + return fromData || fromUrl; + } + + /** + * Build a sign string from top-level fields without serializing the whole payload. + * @param {object|Array} data + * @return {string} + */ + getStructuredJQAjaxSignString(data) { + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return this.getSerializeArraySignString(data); + } + const parts = []; + const action = this.getPlainObjectSignField(data, 'action'); + if ( typeof action === 'string' && action !== '' ) { + parts.push('action=' + action); + } + const nonce = this.getPlainObjectSignField(data, 'ur_frontend_form_nonce'); + if ( nonce !== null ) { + parts.push('ur_frontend_form_nonce=' + nonce); + } + if ( this.plainObjectHasTwtCcSignup(data) ) { + parts.push('twt_cc_signup=1'); + } + return parts.join('&'); + } + + /** + * Read action/nonce from top-level, data[key], or nested data.key. + * @param {object} data + * @param {string} key + * @return {string|number|null} + */ + getPlainObjectSignField(data, key) { + if ( !data || typeof data !== 'object' ) { + return null; + } + if ( this.isJQAjaxScalarSignValue(data[key]) ) { + return data[key]; + } + const bracketKey = 'data[' + key + ']'; + if ( this.isJQAjaxScalarSignValue(data[bracketKey]) ) { + return data[bracketKey]; + } + if ( + data.data && + typeof data.data === 'object' && + Object.prototype.toString.call(data.data) !== '[object Array]' && + this.isJQAjaxScalarSignValue(data.data[key]) + ) { + return data.data[key]; + } + return null; + } + + /** + * @param {*} value + * @return {boolean} + */ + isJQAjaxScalarSignValue(value) { + return typeof value === 'string' || typeof value === 'number'; + } + + /** + * @param {object} data + * @param {number=} depth + * @return {boolean} + */ + plainObjectHasTwtCcSignup(data, depth) { + if ( !data || typeof data !== 'object' ) { + return false; + } + if ( typeof depth === 'undefined' ) { + depth = 0; + } + if ( depth > 2 ) { + return false; + } + for ( const key in data ) { + if ( !Object.prototype.hasOwnProperty.call(data, key) ) { + continue; + } + const normalizedKey = this.unwrapJQAjaxFormDataKey(key); + if ( normalizedKey === 'twt_cc_signup' || key.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + const value = data[key]; + if ( typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + if ( + value && + typeof value === 'object' && + Object.prototype.toString.call(value) !== '[object Array]' + ) { + if ( this.plainObjectHasTwtCcSignup(value, depth + 1) ) { + return true; + } + } + } + return false; + } + + /** + * @param {Array} entries + * @return {string} + */ + getSerializeArraySignString(entries) { + const parts = []; + for ( let i = 0; i < entries.length; i++ ) { + const entry = entries[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + continue; + } + const value = entry.value; + const normalizedKey = this.unwrapJQAjaxFormDataKey(entry.name); + if ( this.isJQAjaxKnownSignField(normalizedKey, value) ) { + parts.push(normalizedKey + '=' + value); + } + } + return parts.join('&'); + } + + /** + * True for serializeArray payloads, including an empty array. + * @param {Array} data + * @return {boolean} + */ + isJQAjaxSerializeArray(data) { + if ( Object.prototype.toString.call(data) !== '[object Array]' ) { + return false; + } + for ( let i = 0; i < data.length; i++ ) { + const entry = data[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + return false; + } + } + return true; + } + + /** + * Cross-realm URLSearchParams (instanceof fails across windows). + * @param {*} data + * @return {boolean} + */ + isJQAjaxURLSearchParams(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object URLSearchParams]' ) { + return true; + } + if ( tag === '[object FormData]' ) { + return false; + } + return typeof data.sort === 'function' && typeof data.get === 'function'; + } + + /** + * Cross-realm FormData, including common polyfills. + * @param {*} data + * @return {boolean} + */ + isJQAjaxFormData(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) || this.isJQAjaxURLSearchParams(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object FormData]' ) { + return true; + } + if ( tag === '[object Headers]' || typeof data.getSetCookie === 'function' ) { + return false; + } + return typeof data.forEach === 'function' || + typeof data.get === 'function' || + typeof data.entries === 'function'; + } + + /** + * Collect only known sign fields from FormData / URLSearchParams. + * Unwrap data[action] so later action=... checks match. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + collectKnownSignStringFromKeyValueBag(bag) { + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' ) { + return; + } + const valueAsString = String(value); + const normalizedKey = unwrapKey(key); + if ( + knownKeys[normalizedKey] || + valueAsString.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + valueAsString); + } + }); + if ( collected ) { + return parts.join('&'); + } + if ( typeof bag.get !== 'function' ) { + return ''; + } + const keysToProbe = [ + 'action', + 'ur_frontend_form_nonce', + 'twt_cc_signup', + ]; + const getParts = []; + for ( let i = 0; i < keysToProbe.length; i++ ) { + const key = keysToProbe[i]; + const value = this.getFormDataScalarValue(bag, [key, 'data[' + key + ']']); + if ( value !== null ) { + getParts.push(key + '=' + value); + } + } + return getParts.join('&'); + } + + /** + * Known sign fields from a request URL query. IE11-safe (no URLSearchParams). + * @param {string} url + * @return {string} + */ + collectKnownSignStringFromUrl(url) { + if ( typeof url !== 'string' || url === '' ) { + return ''; + } + const queryIndex = url.indexOf('?'); + if ( queryIndex === -1 || queryIndex === url.length - 1 ) { + return ''; + } + const hashIndex = url.indexOf('#', queryIndex); + const query = hashIndex === -1 ? + url.slice(queryIndex + 1) : + url.slice(queryIndex + 1, hashIndex); + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const pairs = query.split('&'); + for ( let i = 0; i < pairs.length; i++ ) { + const pair = pairs[i]; + if ( !pair ) { + continue; + } + const eq = pair.indexOf('='); + let rawKey = eq === -1 ? pair : pair.slice(0, eq); + let rawValue = eq === -1 ? '' : pair.slice(eq + 1); + try { + rawKey = decodeURIComponent(rawKey.replace(/\+/g, ' ')); + rawValue = decodeURIComponent(rawValue.replace(/\+/g, ' ')); + } catch (e) { + continue; + } + const normalizedKey = unwrapKey(rawKey); + if ( + knownKeys[normalizedKey] || + rawValue.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + rawValue); + } + } + return parts.join('&'); + } + + /** + * Walk FormData/URLSearchParams via forEach, then entries() for polyfills that only have an iterator. + * @param {FormData|URLSearchParams} bag + * @param {Function} callback + * @return {boolean} + */ + forEachJQAjaxKeyValueBag(bag, callback) { + if ( typeof bag.forEach === 'function' ) { + try { + bag.forEach(callback); + return true; + } catch (e) { + // Fall through to entries(). + } + } + if ( typeof bag.entries !== 'function' ) { + return false; + } + try { + const iterator = bag.entries(); + if ( !iterator || typeof iterator.next !== 'function' ) { + return false; + } + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + callback(pair[1], pair[0]); + } + step = iterator.next(); + } + return true; + } catch (e) { + return false; + } + } + + /** + * @return {Object} + */ + getJQAjaxKnownSignKeys() { + const knownKeys = Object.create(null); + knownKeys.action = true; + knownKeys.ur_frontend_form_nonce = true; + knownKeys.twt_cc_signup = true; + return knownKeys; + } + + /** + * @param {string} normalizedKey + * @param {*} value + * @return {boolean} + */ + isJQAjaxKnownSignField(normalizedKey, value) { + if ( + normalizedKey === 'action' || + normalizedKey === 'ur_frontend_form_nonce' || + normalizedKey === 'twt_cc_signup' || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + return true; + } + return typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1; + } + + /** + * Treat data[action] as action for WP-style payloads. + * @param {string} key + * @return {string} + */ + unwrapJQAjaxFormDataKey(key) { + if ( typeof key !== 'string' ) { + return ''; + } + if ( key.length > 6 && key.indexOf('data[') === 0 && key.charAt(key.length - 1) === ']' ) { + return key.slice(5, -1); + } + return key; + } + + /** + * @param {FormData} formData + * @param {Array.} keys + * @return {string|number|null} + */ + getFormDataScalarValue(formData, keys) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && (typeof value === 'string' || typeof value === 'number') ) { + return value; + } + } + return null; + } + + /** + * True for arrays and plain objects that jQuery.param can serialize safely. + * @param {*} data + * @return {boolean} + */ + isJQAjaxPlainObjectOrArray(data) { + if ( data === null || typeof data !== 'object' ) { + return false; + } + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return true; + } + if ( typeof jQuery !== 'undefined' && typeof jQuery.isPlainObject === 'function' ) { + return jQuery.isPlainObject(data); + } + const proto = Object.getPrototypeOf(data); + return proto === Object.prototype || proto === null; + } + + /** + * Search for sign within AJAX data to do inject CleanTalk data. + * @param {object} ajaxObject Ajax object. + * @param {object=} originalOptions Original jQuery ajax options before merge. + * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + */ + searchSignsForJQAjaxInjection(ajaxObject, originalOptions) { + let sourceSign = { + 'found': false, + 'keepUnwrapped': false, + 'attachVisibleFieldsData': false, + }; + let dataString = this.getJQAjaxDataAsString(ajaxObject); + if ( !dataString && originalOptions && originalOptions !== ajaxObject ) { + dataString = this.getJQAjaxDataAsString(originalOptions); + } + + if ( dataString.indexOf('action=fl_builder_subscribe_form_submit') !== -1 ) { + sourceSign.found = 'fl_builder_subscribe_form_submit'; + } + if ( dataString.indexOf('twt_cc_signup') !== -1 ) { + sourceSign.found = 'twt_cc_signup'; + } + if ( dataString.indexOf('action=mailpoet') !== -1 ) { + sourceSign.found = 'action=mailpoet'; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=user_registration') !== -1 && + dataString.indexOf('ur_frontend_form_nonce') !== -1 + ) { + sourceSign.found = 'action=user_registration'; + } + if ( dataString.indexOf('action=happyforms_message') !== -1 ) { + sourceSign.found = 'action=happyforms_message'; + } + if ( dataString.indexOf('action=new_activity_comment') !== -1 ) { + sourceSign.found = 'action=new_activity_comment'; + } + if ( dataString.indexOf('action=wwlc_create_user') !== -1 ) { + sourceSign.found = 'action=wwlc_create_user'; + } + if ( dataString.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 ) { + sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=drplus_signup') !== -1 ) { + sourceSign.found = 'action=drplus_signup'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=bt_cc') !== -1 ) { + sourceSign.found = 'action=bt_cc'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=wpr_form_builder_email') !== -1 ) { + sourceSign.found = 'action=wpr_form_builder_email'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=nf_ajax_submit') !== -1 ) { + sourceSign.found = 'action=nf_ajax_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=uael_register_user') !== -1 && + ctPublic.data__cookies_type === 'none' + ) { + sourceSign.found = 'action=uael_register_user'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=SQBSubmitQuizAjax') !== -1 ) { + sourceSign.found = 'action=SQBSubmitQuizAjax'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=user_registration_user_form_submit') !== -1 ) { + sourceSign.found = 'action=user_registration_user_form_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=bloom_subscribe') !== -1 ) { + sourceSign.found = 'action=bloom_subscribe'; + sourceSign.keepUnwrapped = true; + } + if ( + this.isJQAjaxFormData(ajaxObject.data) && + typeof ajaxObject.data.get === 'function' && + ajaxObject.data.get('action') === 'pafe_ajax_form_builder' + ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } else if ( dataString.indexOf('action=pafe_ajax_form_builder') !== -1 ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } + + // woocommerce add to cart is based on URL + if ( typeof ajaxObject.url === 'string' && ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1 ) { + sourceSign.found = 'wc-ajax=add_to_cart'; + // GET/HEAD: PHP reads Get::get('ct_bot_detector_event_token'), not data[...]. + if ( this.isJQAjaxNoContentMethod(ajaxObject) ) { + sourceSign.keepUnwrapped = true; + } + } + + return sourceSign; + } + + /** + * Inject CleanTalk data into jQuery ajax payload of any supported type. + * @param {object} sourceSign + * @param {*} ajaxData + * @param {object=} ajaxOptions jQuery ajax options (traditional, processData, contentType). + * Keep URLSearchParams/objects when processData or contentType is false. + * URLSearchParams must also disable processData, or jQuery.param() later yields "". + * GET/HEAD never keep the original type: jQuery only puts string data on the URL. + * @return {*} + */ + injectCleantalkDataToJQAjax(sourceSign, ajaxData, ajaxOptions) { + const traditional = ajaxOptions && ajaxOptions.traditional; + const keepOriginalType = !this.isJQAjaxNoContentMethod(ajaxOptions) && !!(ajaxOptions && ( + ajaxOptions.processData === false || + ajaxOptions.contentType === false + )); + + if ( ajaxData === null || typeof ajaxData === 'undefined' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ''); + } + if ( typeof ajaxData === 'string' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData); + } + if ( this.isJQAjaxPlainObjectOrArray(ajaxData) ) { + if ( keepOriginalType ) { + if ( Object.prototype.toString.call(ajaxData) === '[object Array]' ) { + if ( this.isJQAjaxSerializeArray(ajaxData) ) { + return this.injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData); + } + return ajaxData; + } + return this.injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData); + } + try { + if ( typeof jQuery !== 'undefined' && typeof jQuery.param === 'function' ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + jQuery.param(ajaxData, traditional), + ); + } + } catch (e) { + return ajaxData; + } + return ajaxData; + } + if ( this.isJQAjaxURLSearchParams(ajaxData) ) { + if ( keepOriginalType ) { + this.preserveJQAjaxURLSearchParamsOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxKeyValue( + sourceSign, + this.cloneURLSearchParams(ajaxData), + ); + } + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData.toString()); + } + if ( this.isJQAjaxFormData(ajaxData) ) { + if ( this.isJQAjaxNoContentMethod(ajaxOptions) ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + this.serializeJQAjaxKeyValueBag(ajaxData), + ); + } + this.preserveJQAjaxFormDataOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxFormData( + sourceSign, + this.cloneFormData(ajaxData), + ); + } + return ajaxData; + } + + /** + * GET/HEAD have no body. Missing type is GET (jQuery default). + * @param {object=} ajaxOptions + * @return {boolean} + */ + isJQAjaxNoContentMethod(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return false; + } + const type = ajaxOptions.type || ajaxOptions.method; + if ( typeof type !== 'string' || type === '' ) { + return true; + } + const method = type.toUpperCase(); + return method === 'GET' || method === 'HEAD'; + } + + /** + * Collect CleanTalk fields to append to a key/value payload. + * @param {object} sourceSign + * @return {Array.>} + */ + getCleantalkJQAjaxFieldPairs(sourceSign) { + const pairs = []; + const wrapKey = function(key) { + return sourceSign.keepUnwrapped ? key : 'data[' + key + ']'; + }; + + if ( + +ctPublic.bot_detector_enabled && + apbctLocalStorage.get('bot_detector_event_token') + ) { + const token = this.toolGetEventToken(); + if ( token ) { + pairs.push([wrapKey('ct_bot_detector_event_token'), token]); + } + } else { + const noCookieData = getNoCookieData(); + if ( noCookieData ) { + pairs.push([wrapKey('ct_no_cookie_hidden_field'), noCookieData]); + } + } + + const browserState = apbctGetBrowserStatePair(); + if ( browserState ) { + const browserStateKey = sourceSign.keepUnwrapped ? + browserState.key : + 'data[' + browserState.key + ']'; + pairs.push([browserStateKey, browserState.value]); + } + + return pairs; + } + + /** + * jQuery.param(FormData) after the prefilter yields "". Keep the body as FormData. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxFormDataOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + ajaxOptions.contentType = false; + } + + /** + * jQuery.param(URLSearchParams) after the prefilter yields "". Keep the body as URLSearchParams. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxURLSearchParamsOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + } + + /** + * Read a FormData field via get(), forEach(), or entries(). + * Native IE11 FormData is write-only and cannot be read. + * @param {FormData} formData + * @param {Array.} keys + * @return {*} + */ + getFormDataField(formData, keys) { + if ( typeof formData.get === 'function' ) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && typeof value !== 'undefined' ) { + return value; + } + } + } + if ( typeof formData.forEach === 'function' ) { + let found = null; + formData.forEach(function(value, key) { + if ( found !== null ) { + return; + } + for ( let i = 0; i < keys.length; i++ ) { + if ( key === keys[i] ) { + found = value; + return; } } - - // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === - if ( - +ctPublic.settings__forms__wc_add_to_cart && - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/batch') && - typeof args[1].body === 'string' - ) { - try { - const batchPayload = JSON.parse(args[1].body); - if (batchPayload.requests && Array.isArray(batchPayload.requests)) { - const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); - for (const req of batchPayload.requests) { - const isAddItem = req.path === '/wc/store/v1/cart/add-item'; - if (isAddItem && req.body && fieldPair && fieldPair.key) { - req.body[fieldPair.key] = fieldPair.value; + }); + if ( found !== null ) { + return found; + } + } + if ( typeof formData.entries === 'function' ) { + try { + const iterator = formData.entries(); + if ( iterator && typeof iterator.next === 'function' ) { + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + for ( let i = 0; i < keys.length; i++ ) { + if ( pair[0] === keys[i] ) { + return pair[1]; } } - args[1].body = JSON.stringify(batchPayload); } - } catch (e) { - // Continue even if error + step = iterator.next(); } } - - // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === - preventOriginalFetch = await processIframeCommonFetch(url, args); - - // Return original fetch result if not prevented - if (!preventOriginalFetch) { - return originalFetch.apply(this, args); - } - } catch (error) { - // In case of any error in our interceptor, call original fetch - return originalFetch.apply(this, args); + } catch (e) { + return null; } - }; + } + return null; } /** - * Prepare jQuery.ajaxSetup to add nocookie data to the jQuery ajax request. - * Notes: - * - Do it just once, the ajaxSetup.beforeSend will be overwritten for any calls. - * - Signs of forms need to be caught will be checked during ajaxSetup.settings.data process on send. - * - Any sign of the form HTML of the caller is insignificant in this process. - * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script - * will work independing if jQuery is loaded by CleanTalk or not - * @return {void} + * Clone URLSearchParams so the caller's instance is not mutated. + * @param {URLSearchParams} params + * @return {URLSearchParams} */ - catchJqueryAjax() { - if ( typeof jQuery !== 'undefined') { - // this code run on base ajax rules - so do not work due scripts use it's own ajax object injections - if ( typeof jQuery.ajaxSetup === 'function' ) { - jQuery.ajaxSetup({ - beforeSend: function(xhr, settings) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(settings, 'ajaxSetup'); - if (sourceSign.found !== false) { - settings.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, settings.data); - } - }, - }); + cloneURLSearchParams(params) { + const serialized = typeof params.toString === 'function' ? params.toString() : ''; + if ( typeof params.constructor === 'function' && params.constructor !== Object ) { + try { + return new params.constructor(serialized); + } catch (e) { + // Fall through to the current-window constructor. } - // this code run on ANY ajax on ANY script queue status - // todo Probably move all ajaxSetup actions to ajaxPrefilter - if ( typeof jQuery.ajaxPrefilter === 'function' ) { - jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(options, 'ajaxPrefilter'); - if (sourceSign.found !== false) { - if (typeof options.data === 'string') { - options.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, options.data); - } - if ( - typeof options.data === 'object' && - typeof options.data.append === 'function' - ) { - options.data = handler.injectCleantalkDataToJQAjaxFormData(sourceSign, options.data); - } - } - }); + } + if ( typeof URLSearchParams === 'function' ) { + try { + return new URLSearchParams(serialized); + } catch (e) { + return params; } } + return params; } /** - * Search for sign within AJAX data to do inject CleanTalk data. - * @param {object} ajaxObject Ajax object. - * @param {string} catchOn Function should be catched on. - * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + * Clone FormData when it can be enumerated (forEach or entries); otherwise reuse. + * @param {FormData} formData + * @return {FormData} */ - searchSignsForJQAjaxInjection(ajaxObject, catchOn = 'ajaxSetup') { - let sourceSign = { - 'found': false, - 'keepUnwrapped': false, - 'attachVisibleFieldsData': false, - }; - // on ajaxSetup - if (catchOn === 'ajaxSetup') { - // settings data is string (important!) - if ( typeof ajaxObject.data === 'string' ) { - if ( - ajaxObject.data.indexOf('action=fl_builder_subscribe_form_submit') !== -1 - ) { - sourceSign.found = 'fl_builder_subscribe_form_submit'; - } - if ( - ajaxObject.data.indexOf('twt_cc_signup') !== -1 - ) { - sourceSign.found = 'twt_cc_signup'; - } - if ( - ajaxObject.data.indexOf('action=mailpoet') !== -1 - ) { - sourceSign.found = 'action=mailpoet'; - sourceSign.attachVisibleFieldsData = true; - } - - if ( - ajaxObject.data.indexOf('action=user_registration') !== -1 && - ajaxObject.data.indexOf('ur_frontend_form_nonce') !== -1 - ) { - sourceSign.found = 'action=user_registration'; - } - - if (ajaxObject.data.indexOf('action=happyforms_message') !== -1) { - sourceSign.found = 'action=happyforms_message'; - } + cloneFormData(formData) { + try { + const clone = new FormData(); + const copied = this.forEachJQAjaxKeyValueBag(formData, function(value, key) { + clone.append(key, value); + }); + if ( copied ) { + return clone; + } + } catch (e) { + return formData; + } + return formData; + } - if ( - ajaxObject.data.indexOf('action=new_activity_comment') !== -1 - ) { - sourceSign.found = 'action=new_activity_comment'; - } - if ( - ajaxObject.data.indexOf('action=wwlc_create_user') !== -1 - ) { - sourceSign.found = 'action=wwlc_create_user'; - } - if ( - ajaxObject.data.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 - ) { - sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=drplus_signup') !== -1 - ) { - sourceSign.found = 'action=drplus_signup'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=bt_cc') !== -1 - ) { - sourceSign.found = 'action=bt_cc'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=wpr_form_builder_email') !== -1 - ) { - sourceSign.found = 'action=wpr_form_builder_email'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=nf_ajax_submit') !== -1 - ) { - sourceSign.found = 'action=nf_ajax_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=uael_register_user') !== -1 && - ctPublic.data__cookies_type === 'none' - ) { - sourceSign.found = 'action=uael_register_user'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=SQBSubmitQuizAjax') !== -1 - ) { - sourceSign.found = 'action=SQBSubmitQuizAjax'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=user_registration_user_form_submit') !== -1 - ) { - sourceSign.found = 'action=user_registration_user_form_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } + /** + * Form-urlencoded string from FormData/URLSearchParams. Skip File/Blob values. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + serializeJQAjaxKeyValueBag(bag) { + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { + return; } - // wooocommerce add to cart is based on URL - if ( typeof ajaxObject.url === 'string' ) { - if (ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1) { - sourceSign.found = 'wc-ajax=add_to_cart'; + parts.push(encodeURIComponent(String(key)) + '=' + encodeURIComponent(String(value))); + }); + if ( collected ) { + return parts.join('&'); + } + return ''; + } + + /** + * Inject CleanTalk fields into URLSearchParams without changing the payload type. + * @param {object} sourceSign + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + injectCleantalkDataToJQAjaxKeyValue(sourceSign, params) { + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + params.append(pairs[i][0], pairs[i][1]); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( extractor ) { + const extracted = extractor.extract(params.toString()); + if ( typeof extracted === 'string' ) { + params.append('apbct_visible_fields', extracted); } } } + return params; + } - // on ajaxPrefilter - if (catchOn === 'ajaxPrefilter') { - if (typeof ajaxObject.data === 'string') { - if (ajaxObject.data.indexOf('action=bloom_subscribe') !== -1) { - sourceSign.found = 'action=bloom_subscribe'; - sourceSign.keepUnwrapped = true; + /** + * Inject CleanTalk fields into a jQuery serializeArray payload. + * @param {object} sourceSign + * @param {Array} ajaxData + * @return {Array} + */ + injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData) { + const result = ajaxData.slice(); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result.push({ + name: pairs[i][0], + value: pairs[i][1], + }); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' + ) { + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.push({ + name: 'apbct_visible_fields', + value: extracted, + }); } } + } + return result; + } + /** + * Inject CleanTalk fields into a plain object without changing the payload type. + * @param {object} sourceSign + * @param {object} ajaxData + * @return {object} + */ + injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData) { + const result = typeof jQuery !== 'undefined' && typeof jQuery.extend === 'function' ? + jQuery.extend({}, ajaxData) : + this.clonePlainObject(ajaxData); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result[pairs[i][0]] = pairs[i][1]; + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); if ( - typeof ajaxObject.data === 'object' && - ajaxObject.data !== null && - typeof ajaxObject.data.get === 'function' + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' ) { - if (ajaxObject.data.get('action') === 'pafe_ajax_form_builder') { - sourceSign.found = 'action=pafe_ajax_form_builder'; - sourceSign.keepUnwrapped = true; + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.apbct_visible_fields = extracted; } } } + return result; + } - return sourceSign; + /** + * IE11-safe shallow copy of a plain object. + * @param {object} ajaxData + * @return {object} + */ + clonePlainObject(ajaxData) { + const result = {}; + for ( const key in ajaxData ) { + if ( Object.prototype.hasOwnProperty.call(ajaxData, key) ) { + result[key] = ajaxData[key]; + } + } + return result; } /** @@ -4021,8 +4881,7 @@ class ApbctHandler { injectCleantalkDataToJQAjaxFormData(sourceSign, ajaxDataFormData) { if ( typeof sourceSign !== 'object' || - typeof ajaxDataFormData !== 'object' || - !(ajaxDataFormData instanceof FormData) + !this.isJQAjaxFormData(ajaxDataFormData) ) { return ajaxDataFormData; } @@ -4053,6 +4912,16 @@ class ApbctHandler { } } + // Bot detector browser state + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append(browserState.key, browserState.value); + } else { + ajaxDataFormData.append('data[' + browserState.key + ']', browserState.value); + } + } + // Visible fields if (sourceSign.attachVisibleFieldsData) { let visibleFieldsSearchResult = false; @@ -4060,13 +4929,10 @@ class ApbctHandler { if (extractor) { // Try to find form_id in FormData to find form container and // collect visible fields only inside it - let formId = null; - for (let pair of ajaxDataFormData.entries()) { - if (pair[0] === 'form_id' || pair[0] === 'data[form_id]') { - formId = pair[1]; - break; - } - } + const formId = this.getFormDataField( + ajaxDataFormData, + ['form_id', 'data[form_id]'], + ); let container = null; if (formId && typeof formId === 'string') { // Sanitize formId to prevent selector injection @@ -4111,6 +4977,15 @@ class ApbctHandler { let eventToken = ''; let noCookieData = ''; let visibleFieldsString = ''; + let browserStateString = ''; + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + const browserStateKey = sourceSign.keepUnwrapped ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; + browserStateString = browserStateKey + '=' + encodeURIComponent(browserState.value) + '&'; + } if ( +ctPublic.bot_detector_enabled && @@ -4127,9 +5002,9 @@ class ApbctHandler { } else { noCookieData = getNoCookieData(); if (sourceSign.keepUnwrapped) { - noCookieData = 'ct_no_cookie_hidden_field=' + noCookieData + '&'; + noCookieData = 'ct_no_cookie_hidden_field=' + encodeURIComponent(noCookieData) + '&'; } else { - noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + noCookieData + '&'; + noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + encodeURIComponent(noCookieData) + '&'; } } @@ -4152,7 +5027,7 @@ class ApbctHandler { } } - return noCookieData + eventToken + visibleFieldsString + ajaxDataString; + return noCookieData + eventToken + browserStateString + visibleFieldsString + ajaxDataString; } /** @@ -7317,67 +8192,126 @@ function ctCheckInternalIsExcludedForm(action) { }); } -let botDetectorLogLastUpdate = 0; -let botDetectorLogEventTypesCollected = []; - -// bot_detector frontend_data log alt session saving cron -if ( - ctPublicFunctions.hasOwnProperty('bot_detector_enabled') && - +ctPublicFunctions.bot_detector_enabled && - ctPublicFunctions.hasOwnProperty('data__frontend_data_log_enabled') && - ctPublicFunctions.data__frontend_data_log_enabled == 1 -) { - sendBotDetectorLogToAltSessions(1000); -} - /** - * Send BotDetector logs data to alternative sessions. - * If log_last_update has changed and log contains new event types, the log will be sent to the alternative sessions. - * @param {int} cronStartTimeout delay before cron start - * @param {int} interval check fires on interval + * Bot detector browser state. + * + * The state is passed to the site backend with the current JS->PHP transport and goes + * to the moderate request as sender_info.bot_detector_frontend_data_log. */ -function sendBotDetectorLogToAltSessions(cronStartTimeout = 3000, interval = 1000) { - setTimeout(function() { - setInterval(function() { - const currentLog = apbctLocalStorage.get('ct_bot_detector_frontend_data_log'); - if (needsSaveLogToAltSessions(currentLog)) { - botDetectorLogLastUpdate = currentLog.log_last_update; - // the log will be taken from javascriptclientdata - ctSetAlternativeCookie([], {forceAltCookies: true}); - } - }, interval); - }, cronStartTimeout); -} +class ApbctBrowserState { + static STATE_KEY = 'apbct_browser_state'; + static LOG_KEY = 'ct_bot_detector_frontend_data_log'; + static SCRIPT_SIGNS = { + botd_wrapper_loaded: 'ct-bot-detector-wrapper', + botd_logic_loaded: 'ct-bot-detector.min', + }; + /** + * This LS key is set on bot-detector side + * @type {string} + */ + static TRANSPORT_ENABLED_SIGN_KEY = 'bot_detector_log_transport_enabled'; + static botdWrapperLoaded = 0; + static botdLogicLoaded = 0; -/** - * Check if the log needs to be saved to the alt sessions. If the log has new event types, it will be saved. - * @param {object} currentLog - * @return {boolean} - */ -function needsSaveLogToAltSessions(currentLog) { - if ( - currentLog && currentLog.hasOwnProperty('log_last_update') && - botDetectorLogLastUpdate !== currentLog.log_last_update - ) { - try { - for (let i = 0; i < currentLog.records.length; i++) { - const currentType = currentLog.records[i].frontend_data.js_event; - // check if this event type was already collected - if (currentType !== undefined && botDetectorLogEventTypesCollected.includes(currentType)) { - continue; + /** + * Get the current browser state as a JSON string ready to be transferred. + * @return {string} Empty string if the bot detector is disabled or on any collecting error. + */ + static getFrontendDataLog() { + const prefix = (typeof ctPublicFunctions !== 'undefined' && ctPublicFunctions.cookiePrefix) ? + ctPublicFunctions.cookiePrefix : + ''; + const logKey = prefix + ApbctBrowserState.LOG_KEY; + const noPrefixLogKey = ApbctBrowserState.LOG_KEY; + + if (typeof apbctLocalStorage !== 'undefined' && apbctLocalStorage.get) { + const logObject = apbctLocalStorage.get(logKey) || apbctLocalStorage.get(noPrefixLogKey) || null; + if (logObject && typeof logObject === 'string') { + try { + return JSON.parse(logObject); + } catch (e) { + return ''; } - // add new event type to collection, this type will be sent to the alt sessions further - botDetectorLogEventTypesCollected.push(currentType); - return true; } + return logObject; + } + + let rawLog = localStorage.getItem(logKey); + if (!rawLog) { + rawLog = localStorage.getItem(noPrefixLogKey) || null; + } + + try { + return typeof rawLog === 'string' ? JSON.parse(rawLog) : rawLog; } catch (e) { - console.log('APBCT: bot detector log collection error: ' . e.toString()); + return ''; } } - return false; -} + /** + * + * @return {object} + */ + static asDTO() { + return { + botd_logic_loaded: ApbctBrowserState.botdLogicLoaded, + botd_wrapper_loaded: ApbctBrowserState.botdWrapperLoaded, + frontend_data_log: '', + transport_enabled: 1, + }; + } + + /** + * Look for the bot detector scripts in the page DOM. + * @return {boolean} True if both scripts are found. + */ + static detectScripts() { + if (ApbctBrowserState.botdWrapperLoaded && ApbctBrowserState.botdLogicLoaded) { + return true; + } + + const scripts = document.getElementsByTagName('script'); + + for (let i = 0; i < scripts.length; i++) { + const src = scripts[i].getAttribute('src'); + if (!src) { + continue; + } + if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_wrapper_loaded) !== -1) { + ApbctBrowserState.botdWrapperLoaded = 1; + } else if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_logic_loaded) !== -1) { + ApbctBrowserState.botdLogicLoaded = 1; + } + } + + // The bot detector logic sets this flag on its own start + return !!ApbctBrowserState.botdWrapperLoaded && !!ApbctBrowserState.botdLogicLoaded; + } +} +/** + * Get the browser state as a key/value pair to attach it to an intercepted request. + * @return {{key: string, value: string}|false} False if there is nothing to attach. + */ +function apbctGetBrowserStatePair() { // eslint-disable-line no-unused-vars + try { + ApbctBrowserState.detectScripts(); + let state = ApbctBrowserState.asDTO(); + if ( ApbctBrowserState.botdLogicLoaded ) { + const transportEnabled = localStorage.getItem(ApbctBrowserState.TRANSPORT_ENABLED_SIGN_KEY) === '1'; + if (transportEnabled) { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } else { + state.transport_enabled = 0; + } + } else { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } + return {key: ApbctBrowserState.STATE_KEY, value: JSON.stringify(state)}; + } catch (e) { + return false; + } +} let ctCheckedEmails = {}; let ctCheckedEmailsExist = {}; diff --git a/js/prebuild/apbct-public-bundle_gathering.js b/js/prebuild/apbct-public-bundle_gathering.js index 7384cd88c..62d6987d4 100644 --- a/js/prebuild/apbct-public-bundle_gathering.js +++ b/js/prebuild/apbct-public-bundle_gathering.js @@ -2253,7 +2253,7 @@ function ctSetCookie( cookies, value, expires='') { let listOfCookieNamesToForceAlt = [ 'ct_sfw_pass_key', 'ct_sfw_passed', - 'wordpress_apbct_antibot', + 'apbct_antibot', 'apbct_anticrawler_passed', 'apbct_bot_detector_exist', 'apbct_antiflood_passed', @@ -2642,6 +2642,15 @@ function getNoCookieData() { // eslint-disable-line no-unused-vars let noCookieDataLocal = apbctLocalStorage.getCleanTalkData(); let noCookieDataSession = apbctSessionStorage.getCleanTalkData(); let noCookieData = {...noCookieDataLocal, ...noCookieDataSession}; + + // Bot detector browser state is transferred with the hidden field on the NoCookie mode + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + noCookieData[browserState.key] = browserState.value; + } + } + noCookieData = JSON.stringify(noCookieData); return '_ct_no_cookie_data_' + btoa(unescape(encodeURIComponent(noCookieData))); @@ -2669,7 +2678,21 @@ function getCleanTalkStorageDataArray() { // eslint-disable-line no-unused-vars noCookieDataFromUserActivity = {collecting_user_activity_data: collectingUserActivityData}; } - return {...noCookieDataLocal, ...noCookieDataSession, ...noCookieDataTypo, ...noCookieDataFromUserActivity}; + let browserStateData = {}; + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + browserStateData[browserState.key] = browserState.value; + } + } + + return { + ...noCookieDataLocal, + ...noCookieDataSession, + ...noCookieDataTypo, + ...noCookieDataFromUserActivity, + ...browserStateData, + }; } /** @@ -3314,6 +3337,9 @@ class ApbctHandler { const eventTokenKey = useUnwrappedCleantalkKeys ? 'ct_bot_detector_event_token' : 'data%5Bct_bot_detector_event_token%5D'; + const browserStateKey = useUnwrappedCleantalkKeys ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; if (!( +ctPublic.bot_detector_enabled && @@ -3338,6 +3364,12 @@ class ApbctHandler { } } + const browserState = apbctGetBrowserStatePair(); + if (browserState && body.indexOf('apbct_browser_state') === -1) { + addidionalCleantalkData += '&' + browserStateKey + '=' + + encodeURIComponent(browserState.value); + } + body += addidionalCleantalkData; } @@ -3354,6 +3386,11 @@ class ApbctHandler { body.append('ct_bot_detector_event_token', eventToken); } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState && !body.has(browserState.key)) { + body.append(browserState.key, browserState.value); + } } if (isNeedToAddCleantalkDataCheckJsonData) { @@ -3391,6 +3428,22 @@ class ApbctHandler { } } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + try { + const bodyObj = JSON.parse(body); + if ( + bodyObj && typeof bodyObj === 'object' && + !Object.prototype.hasOwnProperty.call(bodyObj, browserState.key) + ) { + bodyObj[browserState.key] = browserState.value; + body = JSON.stringify(bodyObj); + } + } catch (e) { + // body is not JSON — leave as is + } + } } return originalSend.apply(this, [body]); @@ -3448,6 +3501,11 @@ class ApbctHandler { } else { args[1].body.append('ct_no_cookie_hidden_field', getNoCookieData()); } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + args[1].body.append(browserState.key, browserState.value); + } } } } catch (e) { @@ -3504,6 +3562,22 @@ class ApbctHandler { * @return {string|FormData} Modified body. */ const attachFieldsToBody = function(body, fieldPair = false) { + const fieldPairs = [fieldPair, apbctGetBrowserStatePair()]; + + for (const pair of fieldPairs) { + body = attachFieldPairToBody(body, pair); + } + + return body; + }; + + /** + * Attach a single key/value pair to fetch request body + * @param {string|FormData} body Fetch request data body. + * @param {object|bool} fieldPair Key value to inject. + * @return {string|FormData} Modified body. + */ + const attachFieldPairToBody = function(body, fieldPair = false) { if (fieldPair) { if (body instanceof FormData || typeof body.append === 'function') { body.append(fieldPair.key, fieldPair.value); @@ -3761,255 +3835,1041 @@ class ApbctHandler { // Continue even if error } } - - // === WooCommerce add to cart (direct add-item URL) === - if ( - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/cart/add-item') - ) { - try { - if (+ctPublic.settings__forms__wc_add_to_cart) { - args[1].body = attachFieldsToBody( - args[1].body, - selectFieldsData(+ctPublic.bot_detector_enabled), - ); - } - } catch (e) { - // Continue even if error + + // === WooCommerce add to cart (direct add-item URL) === + if ( + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/cart/add-item') + ) { + try { + if (+ctPublic.settings__forms__wc_add_to_cart) { + args[1].body = attachFieldsToBody( + args[1].body, + selectFieldsData(+ctPublic.bot_detector_enabled), + ); + } + } catch (e) { + // Continue even if error + } + } + + // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === + if ( + +ctPublic.settings__forms__wc_add_to_cart && + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/batch') && + typeof args[1].body === 'string' + ) { + try { + const batchPayload = JSON.parse(args[1].body); + if (batchPayload.requests && Array.isArray(batchPayload.requests)) { + const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); + const browserState = apbctGetBrowserStatePair(); + for (const req of batchPayload.requests) { + const isAddItem = req.path === '/wc/store/v1/cart/add-item'; + if (isAddItem && req.body && fieldPair && fieldPair.key) { + req.body[fieldPair.key] = fieldPair.value; + } + if (isAddItem && req.body && browserState) { + req.body[browserState.key] = browserState.value; + } + } + args[1].body = JSON.stringify(batchPayload); + } + } catch (e) { + // Continue even if error + } + } + + // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === + preventOriginalFetch = await processIframeCommonFetch(url, args); + + // Return original fetch result if not prevented + if (!preventOriginalFetch) { + return originalFetch.apply(this, args); + } + } catch (error) { + // In case of any error in our interceptor, call original fetch + return originalFetch.apply(this, args); + } + }; + } + + /** + * Prepare jQuery.ajaxPrefilter to add CleanTalk data to jQuery ajax requests. + * Notes: + * - ajaxSetup.beforeSend is not used: a request can supply its own beforeSend and drop the default. + * - ajaxPrefilter runs for every jQuery ajax call after options are merged, so injection is guaranteed. + * - Form signs are checked on the request data/url at send time. + * - Any sign of the form HTML of the caller is insignificant in this process. + * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script + * will work independing if jQuery is loaded by CleanTalk or not + * @return {void} + */ + catchJqueryAjax() { + if ( typeof jQuery !== 'undefined' && typeof jQuery.ajaxPrefilter === 'function' ) { + jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { + const handler = new ApbctHandler(); + const sourceSign = handler.searchSignsForJQAjaxInjection(options, originalOptions); + if (sourceSign.found !== false) { + options.data = handler.injectCleantalkDataToJQAjax( + sourceSign, + handler.getJQAjaxPayloadForInject(options, originalOptions), + options, + ); + } + }); + } + } + + /** + * jQuery.param() on URLSearchParams/FormData can collapse options.data to "". + * Sign search already falls back to originalOptions; inject must use that payload too. + * @param {object} options + * @param {object=} originalOptions + * @return {*} + */ + getJQAjaxPayloadForInject(options, originalOptions) { + const current = options && options.data; + const original = originalOptions && originalOptions.data; + if ( this.jqAjaxPayloadWasCollapsed(current, original) ) { + return original; + } + return current; + } + + /** + * @param {*} current + * @param {*} original + * @return {boolean} + */ + jqAjaxPayloadWasCollapsed(current, original) { + if ( original === null || typeof original === 'undefined' ) { + return false; + } + if ( current === original ) { + return false; + } + const currentEmpty = current === '' || current === null || typeof current === 'undefined'; + if ( !currentEmpty ) { + return false; + } + if ( typeof original === 'string' ) { + return original !== ''; + } + return this.isJQAjaxFormData(original) || + this.isJQAjaxURLSearchParams(original) || + this.isJQAjaxPlainObjectOrArray(original); + } + + /** + * Normalize jQuery ajax data to a query string for sign search. + * Objects and serializeArray are read structurally so search never calls jQuery.param. + * Also reads known sign fields from the URL (IE11 FormData cannot be enumerated). + * @param {object} ajaxObject Ajax options object. + * @return {string} + */ + getJQAjaxDataAsString(ajaxObject) { + if ( !ajaxObject || typeof ajaxObject !== 'object' ) { + return ''; + } + let fromData = ''; + if ( typeof ajaxObject.data === 'string' ) { + fromData = ajaxObject.data; + } else if ( this.isJQAjaxPlainObjectOrArray(ajaxObject.data) ) { + fromData = this.getStructuredJQAjaxSignString(ajaxObject.data); + } else if ( this.isJQAjaxURLSearchParams(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } else if ( this.isJQAjaxFormData(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } + // Native IE11 FormData is write-only (no get/forEach/entries). Signs then come from the URL. + const fromUrl = this.collectKnownSignStringFromUrl(ajaxObject.url); + if ( fromData && fromUrl ) { + return fromData + '&' + fromUrl; + } + return fromData || fromUrl; + } + + /** + * Build a sign string from top-level fields without serializing the whole payload. + * @param {object|Array} data + * @return {string} + */ + getStructuredJQAjaxSignString(data) { + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return this.getSerializeArraySignString(data); + } + const parts = []; + const action = this.getPlainObjectSignField(data, 'action'); + if ( typeof action === 'string' && action !== '' ) { + parts.push('action=' + action); + } + const nonce = this.getPlainObjectSignField(data, 'ur_frontend_form_nonce'); + if ( nonce !== null ) { + parts.push('ur_frontend_form_nonce=' + nonce); + } + if ( this.plainObjectHasTwtCcSignup(data) ) { + parts.push('twt_cc_signup=1'); + } + return parts.join('&'); + } + + /** + * Read action/nonce from top-level, data[key], or nested data.key. + * @param {object} data + * @param {string} key + * @return {string|number|null} + */ + getPlainObjectSignField(data, key) { + if ( !data || typeof data !== 'object' ) { + return null; + } + if ( this.isJQAjaxScalarSignValue(data[key]) ) { + return data[key]; + } + const bracketKey = 'data[' + key + ']'; + if ( this.isJQAjaxScalarSignValue(data[bracketKey]) ) { + return data[bracketKey]; + } + if ( + data.data && + typeof data.data === 'object' && + Object.prototype.toString.call(data.data) !== '[object Array]' && + this.isJQAjaxScalarSignValue(data.data[key]) + ) { + return data.data[key]; + } + return null; + } + + /** + * @param {*} value + * @return {boolean} + */ + isJQAjaxScalarSignValue(value) { + return typeof value === 'string' || typeof value === 'number'; + } + + /** + * @param {object} data + * @param {number=} depth + * @return {boolean} + */ + plainObjectHasTwtCcSignup(data, depth) { + if ( !data || typeof data !== 'object' ) { + return false; + } + if ( typeof depth === 'undefined' ) { + depth = 0; + } + if ( depth > 2 ) { + return false; + } + for ( const key in data ) { + if ( !Object.prototype.hasOwnProperty.call(data, key) ) { + continue; + } + const normalizedKey = this.unwrapJQAjaxFormDataKey(key); + if ( normalizedKey === 'twt_cc_signup' || key.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + const value = data[key]; + if ( typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + if ( + value && + typeof value === 'object' && + Object.prototype.toString.call(value) !== '[object Array]' + ) { + if ( this.plainObjectHasTwtCcSignup(value, depth + 1) ) { + return true; + } + } + } + return false; + } + + /** + * @param {Array} entries + * @return {string} + */ + getSerializeArraySignString(entries) { + const parts = []; + for ( let i = 0; i < entries.length; i++ ) { + const entry = entries[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + continue; + } + const value = entry.value; + const normalizedKey = this.unwrapJQAjaxFormDataKey(entry.name); + if ( this.isJQAjaxKnownSignField(normalizedKey, value) ) { + parts.push(normalizedKey + '=' + value); + } + } + return parts.join('&'); + } + + /** + * True for serializeArray payloads, including an empty array. + * @param {Array} data + * @return {boolean} + */ + isJQAjaxSerializeArray(data) { + if ( Object.prototype.toString.call(data) !== '[object Array]' ) { + return false; + } + for ( let i = 0; i < data.length; i++ ) { + const entry = data[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + return false; + } + } + return true; + } + + /** + * Cross-realm URLSearchParams (instanceof fails across windows). + * @param {*} data + * @return {boolean} + */ + isJQAjaxURLSearchParams(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object URLSearchParams]' ) { + return true; + } + if ( tag === '[object FormData]' ) { + return false; + } + return typeof data.sort === 'function' && typeof data.get === 'function'; + } + + /** + * Cross-realm FormData, including common polyfills. + * @param {*} data + * @return {boolean} + */ + isJQAjaxFormData(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) || this.isJQAjaxURLSearchParams(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object FormData]' ) { + return true; + } + if ( tag === '[object Headers]' || typeof data.getSetCookie === 'function' ) { + return false; + } + return typeof data.forEach === 'function' || + typeof data.get === 'function' || + typeof data.entries === 'function'; + } + + /** + * Collect only known sign fields from FormData / URLSearchParams. + * Unwrap data[action] so later action=... checks match. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + collectKnownSignStringFromKeyValueBag(bag) { + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' ) { + return; + } + const valueAsString = String(value); + const normalizedKey = unwrapKey(key); + if ( + knownKeys[normalizedKey] || + valueAsString.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + valueAsString); + } + }); + if ( collected ) { + return parts.join('&'); + } + if ( typeof bag.get !== 'function' ) { + return ''; + } + const keysToProbe = [ + 'action', + 'ur_frontend_form_nonce', + 'twt_cc_signup', + ]; + const getParts = []; + for ( let i = 0; i < keysToProbe.length; i++ ) { + const key = keysToProbe[i]; + const value = this.getFormDataScalarValue(bag, [key, 'data[' + key + ']']); + if ( value !== null ) { + getParts.push(key + '=' + value); + } + } + return getParts.join('&'); + } + + /** + * Known sign fields from a request URL query. IE11-safe (no URLSearchParams). + * @param {string} url + * @return {string} + */ + collectKnownSignStringFromUrl(url) { + if ( typeof url !== 'string' || url === '' ) { + return ''; + } + const queryIndex = url.indexOf('?'); + if ( queryIndex === -1 || queryIndex === url.length - 1 ) { + return ''; + } + const hashIndex = url.indexOf('#', queryIndex); + const query = hashIndex === -1 ? + url.slice(queryIndex + 1) : + url.slice(queryIndex + 1, hashIndex); + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const pairs = query.split('&'); + for ( let i = 0; i < pairs.length; i++ ) { + const pair = pairs[i]; + if ( !pair ) { + continue; + } + const eq = pair.indexOf('='); + let rawKey = eq === -1 ? pair : pair.slice(0, eq); + let rawValue = eq === -1 ? '' : pair.slice(eq + 1); + try { + rawKey = decodeURIComponent(rawKey.replace(/\+/g, ' ')); + rawValue = decodeURIComponent(rawValue.replace(/\+/g, ' ')); + } catch (e) { + continue; + } + const normalizedKey = unwrapKey(rawKey); + if ( + knownKeys[normalizedKey] || + rawValue.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + rawValue); + } + } + return parts.join('&'); + } + + /** + * Walk FormData/URLSearchParams via forEach, then entries() for polyfills that only have an iterator. + * @param {FormData|URLSearchParams} bag + * @param {Function} callback + * @return {boolean} + */ + forEachJQAjaxKeyValueBag(bag, callback) { + if ( typeof bag.forEach === 'function' ) { + try { + bag.forEach(callback); + return true; + } catch (e) { + // Fall through to entries(). + } + } + if ( typeof bag.entries !== 'function' ) { + return false; + } + try { + const iterator = bag.entries(); + if ( !iterator || typeof iterator.next !== 'function' ) { + return false; + } + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + callback(pair[1], pair[0]); + } + step = iterator.next(); + } + return true; + } catch (e) { + return false; + } + } + + /** + * @return {Object} + */ + getJQAjaxKnownSignKeys() { + const knownKeys = Object.create(null); + knownKeys.action = true; + knownKeys.ur_frontend_form_nonce = true; + knownKeys.twt_cc_signup = true; + return knownKeys; + } + + /** + * @param {string} normalizedKey + * @param {*} value + * @return {boolean} + */ + isJQAjaxKnownSignField(normalizedKey, value) { + if ( + normalizedKey === 'action' || + normalizedKey === 'ur_frontend_form_nonce' || + normalizedKey === 'twt_cc_signup' || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + return true; + } + return typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1; + } + + /** + * Treat data[action] as action for WP-style payloads. + * @param {string} key + * @return {string} + */ + unwrapJQAjaxFormDataKey(key) { + if ( typeof key !== 'string' ) { + return ''; + } + if ( key.length > 6 && key.indexOf('data[') === 0 && key.charAt(key.length - 1) === ']' ) { + return key.slice(5, -1); + } + return key; + } + + /** + * @param {FormData} formData + * @param {Array.} keys + * @return {string|number|null} + */ + getFormDataScalarValue(formData, keys) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && (typeof value === 'string' || typeof value === 'number') ) { + return value; + } + } + return null; + } + + /** + * True for arrays and plain objects that jQuery.param can serialize safely. + * @param {*} data + * @return {boolean} + */ + isJQAjaxPlainObjectOrArray(data) { + if ( data === null || typeof data !== 'object' ) { + return false; + } + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return true; + } + if ( typeof jQuery !== 'undefined' && typeof jQuery.isPlainObject === 'function' ) { + return jQuery.isPlainObject(data); + } + const proto = Object.getPrototypeOf(data); + return proto === Object.prototype || proto === null; + } + + /** + * Search for sign within AJAX data to do inject CleanTalk data. + * @param {object} ajaxObject Ajax object. + * @param {object=} originalOptions Original jQuery ajax options before merge. + * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + */ + searchSignsForJQAjaxInjection(ajaxObject, originalOptions) { + let sourceSign = { + 'found': false, + 'keepUnwrapped': false, + 'attachVisibleFieldsData': false, + }; + let dataString = this.getJQAjaxDataAsString(ajaxObject); + if ( !dataString && originalOptions && originalOptions !== ajaxObject ) { + dataString = this.getJQAjaxDataAsString(originalOptions); + } + + if ( dataString.indexOf('action=fl_builder_subscribe_form_submit') !== -1 ) { + sourceSign.found = 'fl_builder_subscribe_form_submit'; + } + if ( dataString.indexOf('twt_cc_signup') !== -1 ) { + sourceSign.found = 'twt_cc_signup'; + } + if ( dataString.indexOf('action=mailpoet') !== -1 ) { + sourceSign.found = 'action=mailpoet'; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=user_registration') !== -1 && + dataString.indexOf('ur_frontend_form_nonce') !== -1 + ) { + sourceSign.found = 'action=user_registration'; + } + if ( dataString.indexOf('action=happyforms_message') !== -1 ) { + sourceSign.found = 'action=happyforms_message'; + } + if ( dataString.indexOf('action=new_activity_comment') !== -1 ) { + sourceSign.found = 'action=new_activity_comment'; + } + if ( dataString.indexOf('action=wwlc_create_user') !== -1 ) { + sourceSign.found = 'action=wwlc_create_user'; + } + if ( dataString.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 ) { + sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=drplus_signup') !== -1 ) { + sourceSign.found = 'action=drplus_signup'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=bt_cc') !== -1 ) { + sourceSign.found = 'action=bt_cc'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=wpr_form_builder_email') !== -1 ) { + sourceSign.found = 'action=wpr_form_builder_email'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=nf_ajax_submit') !== -1 ) { + sourceSign.found = 'action=nf_ajax_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=uael_register_user') !== -1 && + ctPublic.data__cookies_type === 'none' + ) { + sourceSign.found = 'action=uael_register_user'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=SQBSubmitQuizAjax') !== -1 ) { + sourceSign.found = 'action=SQBSubmitQuizAjax'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=user_registration_user_form_submit') !== -1 ) { + sourceSign.found = 'action=user_registration_user_form_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=bloom_subscribe') !== -1 ) { + sourceSign.found = 'action=bloom_subscribe'; + sourceSign.keepUnwrapped = true; + } + if ( + this.isJQAjaxFormData(ajaxObject.data) && + typeof ajaxObject.data.get === 'function' && + ajaxObject.data.get('action') === 'pafe_ajax_form_builder' + ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } else if ( dataString.indexOf('action=pafe_ajax_form_builder') !== -1 ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } + + // woocommerce add to cart is based on URL + if ( typeof ajaxObject.url === 'string' && ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1 ) { + sourceSign.found = 'wc-ajax=add_to_cart'; + // GET/HEAD: PHP reads Get::get('ct_bot_detector_event_token'), not data[...]. + if ( this.isJQAjaxNoContentMethod(ajaxObject) ) { + sourceSign.keepUnwrapped = true; + } + } + + return sourceSign; + } + + /** + * Inject CleanTalk data into jQuery ajax payload of any supported type. + * @param {object} sourceSign + * @param {*} ajaxData + * @param {object=} ajaxOptions jQuery ajax options (traditional, processData, contentType). + * Keep URLSearchParams/objects when processData or contentType is false. + * URLSearchParams must also disable processData, or jQuery.param() later yields "". + * GET/HEAD never keep the original type: jQuery only puts string data on the URL. + * @return {*} + */ + injectCleantalkDataToJQAjax(sourceSign, ajaxData, ajaxOptions) { + const traditional = ajaxOptions && ajaxOptions.traditional; + const keepOriginalType = !this.isJQAjaxNoContentMethod(ajaxOptions) && !!(ajaxOptions && ( + ajaxOptions.processData === false || + ajaxOptions.contentType === false + )); + + if ( ajaxData === null || typeof ajaxData === 'undefined' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ''); + } + if ( typeof ajaxData === 'string' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData); + } + if ( this.isJQAjaxPlainObjectOrArray(ajaxData) ) { + if ( keepOriginalType ) { + if ( Object.prototype.toString.call(ajaxData) === '[object Array]' ) { + if ( this.isJQAjaxSerializeArray(ajaxData) ) { + return this.injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData); + } + return ajaxData; + } + return this.injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData); + } + try { + if ( typeof jQuery !== 'undefined' && typeof jQuery.param === 'function' ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + jQuery.param(ajaxData, traditional), + ); + } + } catch (e) { + return ajaxData; + } + return ajaxData; + } + if ( this.isJQAjaxURLSearchParams(ajaxData) ) { + if ( keepOriginalType ) { + this.preserveJQAjaxURLSearchParamsOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxKeyValue( + sourceSign, + this.cloneURLSearchParams(ajaxData), + ); + } + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData.toString()); + } + if ( this.isJQAjaxFormData(ajaxData) ) { + if ( this.isJQAjaxNoContentMethod(ajaxOptions) ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + this.serializeJQAjaxKeyValueBag(ajaxData), + ); + } + this.preserveJQAjaxFormDataOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxFormData( + sourceSign, + this.cloneFormData(ajaxData), + ); + } + return ajaxData; + } + + /** + * GET/HEAD have no body. Missing type is GET (jQuery default). + * @param {object=} ajaxOptions + * @return {boolean} + */ + isJQAjaxNoContentMethod(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return false; + } + const type = ajaxOptions.type || ajaxOptions.method; + if ( typeof type !== 'string' || type === '' ) { + return true; + } + const method = type.toUpperCase(); + return method === 'GET' || method === 'HEAD'; + } + + /** + * Collect CleanTalk fields to append to a key/value payload. + * @param {object} sourceSign + * @return {Array.>} + */ + getCleantalkJQAjaxFieldPairs(sourceSign) { + const pairs = []; + const wrapKey = function(key) { + return sourceSign.keepUnwrapped ? key : 'data[' + key + ']'; + }; + + if ( + +ctPublic.bot_detector_enabled && + apbctLocalStorage.get('bot_detector_event_token') + ) { + const token = this.toolGetEventToken(); + if ( token ) { + pairs.push([wrapKey('ct_bot_detector_event_token'), token]); + } + } else { + const noCookieData = getNoCookieData(); + if ( noCookieData ) { + pairs.push([wrapKey('ct_no_cookie_hidden_field'), noCookieData]); + } + } + + const browserState = apbctGetBrowserStatePair(); + if ( browserState ) { + const browserStateKey = sourceSign.keepUnwrapped ? + browserState.key : + 'data[' + browserState.key + ']'; + pairs.push([browserStateKey, browserState.value]); + } + + return pairs; + } + + /** + * jQuery.param(FormData) after the prefilter yields "". Keep the body as FormData. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxFormDataOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + ajaxOptions.contentType = false; + } + + /** + * jQuery.param(URLSearchParams) after the prefilter yields "". Keep the body as URLSearchParams. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxURLSearchParamsOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + } + + /** + * Read a FormData field via get(), forEach(), or entries(). + * Native IE11 FormData is write-only and cannot be read. + * @param {FormData} formData + * @param {Array.} keys + * @return {*} + */ + getFormDataField(formData, keys) { + if ( typeof formData.get === 'function' ) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && typeof value !== 'undefined' ) { + return value; + } + } + } + if ( typeof formData.forEach === 'function' ) { + let found = null; + formData.forEach(function(value, key) { + if ( found !== null ) { + return; + } + for ( let i = 0; i < keys.length; i++ ) { + if ( key === keys[i] ) { + found = value; + return; } } - - // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === - if ( - +ctPublic.settings__forms__wc_add_to_cart && - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/batch') && - typeof args[1].body === 'string' - ) { - try { - const batchPayload = JSON.parse(args[1].body); - if (batchPayload.requests && Array.isArray(batchPayload.requests)) { - const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); - for (const req of batchPayload.requests) { - const isAddItem = req.path === '/wc/store/v1/cart/add-item'; - if (isAddItem && req.body && fieldPair && fieldPair.key) { - req.body[fieldPair.key] = fieldPair.value; + }); + if ( found !== null ) { + return found; + } + } + if ( typeof formData.entries === 'function' ) { + try { + const iterator = formData.entries(); + if ( iterator && typeof iterator.next === 'function' ) { + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + for ( let i = 0; i < keys.length; i++ ) { + if ( pair[0] === keys[i] ) { + return pair[1]; } } - args[1].body = JSON.stringify(batchPayload); } - } catch (e) { - // Continue even if error + step = iterator.next(); } } - - // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === - preventOriginalFetch = await processIframeCommonFetch(url, args); - - // Return original fetch result if not prevented - if (!preventOriginalFetch) { - return originalFetch.apply(this, args); - } - } catch (error) { - // In case of any error in our interceptor, call original fetch - return originalFetch.apply(this, args); + } catch (e) { + return null; } - }; + } + return null; } /** - * Prepare jQuery.ajaxSetup to add nocookie data to the jQuery ajax request. - * Notes: - * - Do it just once, the ajaxSetup.beforeSend will be overwritten for any calls. - * - Signs of forms need to be caught will be checked during ajaxSetup.settings.data process on send. - * - Any sign of the form HTML of the caller is insignificant in this process. - * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script - * will work independing if jQuery is loaded by CleanTalk or not - * @return {void} + * Clone URLSearchParams so the caller's instance is not mutated. + * @param {URLSearchParams} params + * @return {URLSearchParams} */ - catchJqueryAjax() { - if ( typeof jQuery !== 'undefined') { - // this code run on base ajax rules - so do not work due scripts use it's own ajax object injections - if ( typeof jQuery.ajaxSetup === 'function' ) { - jQuery.ajaxSetup({ - beforeSend: function(xhr, settings) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(settings, 'ajaxSetup'); - if (sourceSign.found !== false) { - settings.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, settings.data); - } - }, - }); + cloneURLSearchParams(params) { + const serialized = typeof params.toString === 'function' ? params.toString() : ''; + if ( typeof params.constructor === 'function' && params.constructor !== Object ) { + try { + return new params.constructor(serialized); + } catch (e) { + // Fall through to the current-window constructor. } - // this code run on ANY ajax on ANY script queue status - // todo Probably move all ajaxSetup actions to ajaxPrefilter - if ( typeof jQuery.ajaxPrefilter === 'function' ) { - jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(options, 'ajaxPrefilter'); - if (sourceSign.found !== false) { - if (typeof options.data === 'string') { - options.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, options.data); - } - if ( - typeof options.data === 'object' && - typeof options.data.append === 'function' - ) { - options.data = handler.injectCleantalkDataToJQAjaxFormData(sourceSign, options.data); - } - } - }); + } + if ( typeof URLSearchParams === 'function' ) { + try { + return new URLSearchParams(serialized); + } catch (e) { + return params; } } + return params; } /** - * Search for sign within AJAX data to do inject CleanTalk data. - * @param {object} ajaxObject Ajax object. - * @param {string} catchOn Function should be catched on. - * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + * Clone FormData when it can be enumerated (forEach or entries); otherwise reuse. + * @param {FormData} formData + * @return {FormData} */ - searchSignsForJQAjaxInjection(ajaxObject, catchOn = 'ajaxSetup') { - let sourceSign = { - 'found': false, - 'keepUnwrapped': false, - 'attachVisibleFieldsData': false, - }; - // on ajaxSetup - if (catchOn === 'ajaxSetup') { - // settings data is string (important!) - if ( typeof ajaxObject.data === 'string' ) { - if ( - ajaxObject.data.indexOf('action=fl_builder_subscribe_form_submit') !== -1 - ) { - sourceSign.found = 'fl_builder_subscribe_form_submit'; - } - if ( - ajaxObject.data.indexOf('twt_cc_signup') !== -1 - ) { - sourceSign.found = 'twt_cc_signup'; - } - if ( - ajaxObject.data.indexOf('action=mailpoet') !== -1 - ) { - sourceSign.found = 'action=mailpoet'; - sourceSign.attachVisibleFieldsData = true; - } - - if ( - ajaxObject.data.indexOf('action=user_registration') !== -1 && - ajaxObject.data.indexOf('ur_frontend_form_nonce') !== -1 - ) { - sourceSign.found = 'action=user_registration'; - } - - if (ajaxObject.data.indexOf('action=happyforms_message') !== -1) { - sourceSign.found = 'action=happyforms_message'; - } + cloneFormData(formData) { + try { + const clone = new FormData(); + const copied = this.forEachJQAjaxKeyValueBag(formData, function(value, key) { + clone.append(key, value); + }); + if ( copied ) { + return clone; + } + } catch (e) { + return formData; + } + return formData; + } - if ( - ajaxObject.data.indexOf('action=new_activity_comment') !== -1 - ) { - sourceSign.found = 'action=new_activity_comment'; - } - if ( - ajaxObject.data.indexOf('action=wwlc_create_user') !== -1 - ) { - sourceSign.found = 'action=wwlc_create_user'; - } - if ( - ajaxObject.data.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 - ) { - sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=drplus_signup') !== -1 - ) { - sourceSign.found = 'action=drplus_signup'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=bt_cc') !== -1 - ) { - sourceSign.found = 'action=bt_cc'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=wpr_form_builder_email') !== -1 - ) { - sourceSign.found = 'action=wpr_form_builder_email'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=nf_ajax_submit') !== -1 - ) { - sourceSign.found = 'action=nf_ajax_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=uael_register_user') !== -1 && - ctPublic.data__cookies_type === 'none' - ) { - sourceSign.found = 'action=uael_register_user'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=SQBSubmitQuizAjax') !== -1 - ) { - sourceSign.found = 'action=SQBSubmitQuizAjax'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=user_registration_user_form_submit') !== -1 - ) { - sourceSign.found = 'action=user_registration_user_form_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } + /** + * Form-urlencoded string from FormData/URLSearchParams. Skip File/Blob values. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + serializeJQAjaxKeyValueBag(bag) { + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { + return; } - // wooocommerce add to cart is based on URL - if ( typeof ajaxObject.url === 'string' ) { - if (ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1) { - sourceSign.found = 'wc-ajax=add_to_cart'; + parts.push(encodeURIComponent(String(key)) + '=' + encodeURIComponent(String(value))); + }); + if ( collected ) { + return parts.join('&'); + } + return ''; + } + + /** + * Inject CleanTalk fields into URLSearchParams without changing the payload type. + * @param {object} sourceSign + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + injectCleantalkDataToJQAjaxKeyValue(sourceSign, params) { + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + params.append(pairs[i][0], pairs[i][1]); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( extractor ) { + const extracted = extractor.extract(params.toString()); + if ( typeof extracted === 'string' ) { + params.append('apbct_visible_fields', extracted); } } } + return params; + } - // on ajaxPrefilter - if (catchOn === 'ajaxPrefilter') { - if (typeof ajaxObject.data === 'string') { - if (ajaxObject.data.indexOf('action=bloom_subscribe') !== -1) { - sourceSign.found = 'action=bloom_subscribe'; - sourceSign.keepUnwrapped = true; + /** + * Inject CleanTalk fields into a jQuery serializeArray payload. + * @param {object} sourceSign + * @param {Array} ajaxData + * @return {Array} + */ + injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData) { + const result = ajaxData.slice(); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result.push({ + name: pairs[i][0], + value: pairs[i][1], + }); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' + ) { + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.push({ + name: 'apbct_visible_fields', + value: extracted, + }); } } + } + return result; + } + /** + * Inject CleanTalk fields into a plain object without changing the payload type. + * @param {object} sourceSign + * @param {object} ajaxData + * @return {object} + */ + injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData) { + const result = typeof jQuery !== 'undefined' && typeof jQuery.extend === 'function' ? + jQuery.extend({}, ajaxData) : + this.clonePlainObject(ajaxData); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result[pairs[i][0]] = pairs[i][1]; + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); if ( - typeof ajaxObject.data === 'object' && - ajaxObject.data !== null && - typeof ajaxObject.data.get === 'function' + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' ) { - if (ajaxObject.data.get('action') === 'pafe_ajax_form_builder') { - sourceSign.found = 'action=pafe_ajax_form_builder'; - sourceSign.keepUnwrapped = true; + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.apbct_visible_fields = extracted; } } } + return result; + } - return sourceSign; + /** + * IE11-safe shallow copy of a plain object. + * @param {object} ajaxData + * @return {object} + */ + clonePlainObject(ajaxData) { + const result = {}; + for ( const key in ajaxData ) { + if ( Object.prototype.hasOwnProperty.call(ajaxData, key) ) { + result[key] = ajaxData[key]; + } + } + return result; } /** @@ -4021,8 +4881,7 @@ class ApbctHandler { injectCleantalkDataToJQAjaxFormData(sourceSign, ajaxDataFormData) { if ( typeof sourceSign !== 'object' || - typeof ajaxDataFormData !== 'object' || - !(ajaxDataFormData instanceof FormData) + !this.isJQAjaxFormData(ajaxDataFormData) ) { return ajaxDataFormData; } @@ -4053,6 +4912,16 @@ class ApbctHandler { } } + // Bot detector browser state + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append(browserState.key, browserState.value); + } else { + ajaxDataFormData.append('data[' + browserState.key + ']', browserState.value); + } + } + // Visible fields if (sourceSign.attachVisibleFieldsData) { let visibleFieldsSearchResult = false; @@ -4060,13 +4929,10 @@ class ApbctHandler { if (extractor) { // Try to find form_id in FormData to find form container and // collect visible fields only inside it - let formId = null; - for (let pair of ajaxDataFormData.entries()) { - if (pair[0] === 'form_id' || pair[0] === 'data[form_id]') { - formId = pair[1]; - break; - } - } + const formId = this.getFormDataField( + ajaxDataFormData, + ['form_id', 'data[form_id]'], + ); let container = null; if (formId && typeof formId === 'string') { // Sanitize formId to prevent selector injection @@ -4111,6 +4977,15 @@ class ApbctHandler { let eventToken = ''; let noCookieData = ''; let visibleFieldsString = ''; + let browserStateString = ''; + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + const browserStateKey = sourceSign.keepUnwrapped ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; + browserStateString = browserStateKey + '=' + encodeURIComponent(browserState.value) + '&'; + } if ( +ctPublic.bot_detector_enabled && @@ -4127,9 +5002,9 @@ class ApbctHandler { } else { noCookieData = getNoCookieData(); if (sourceSign.keepUnwrapped) { - noCookieData = 'ct_no_cookie_hidden_field=' + noCookieData + '&'; + noCookieData = 'ct_no_cookie_hidden_field=' + encodeURIComponent(noCookieData) + '&'; } else { - noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + noCookieData + '&'; + noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + encodeURIComponent(noCookieData) + '&'; } } @@ -4152,7 +5027,7 @@ class ApbctHandler { } } - return noCookieData + eventToken + visibleFieldsString + ajaxDataString; + return noCookieData + eventToken + browserStateString + visibleFieldsString + ajaxDataString; } /** @@ -5732,67 +6607,126 @@ function apbctCancelAutocomplete(element) { })); } -let botDetectorLogLastUpdate = 0; -let botDetectorLogEventTypesCollected = []; - -// bot_detector frontend_data log alt session saving cron -if ( - ctPublicFunctions.hasOwnProperty('bot_detector_enabled') && - +ctPublicFunctions.bot_detector_enabled && - ctPublicFunctions.hasOwnProperty('data__frontend_data_log_enabled') && - ctPublicFunctions.data__frontend_data_log_enabled == 1 -) { - sendBotDetectorLogToAltSessions(1000); -} - /** - * Send BotDetector logs data to alternative sessions. - * If log_last_update has changed and log contains new event types, the log will be sent to the alternative sessions. - * @param {int} cronStartTimeout delay before cron start - * @param {int} interval check fires on interval + * Bot detector browser state. + * + * The state is passed to the site backend with the current JS->PHP transport and goes + * to the moderate request as sender_info.bot_detector_frontend_data_log. */ -function sendBotDetectorLogToAltSessions(cronStartTimeout = 3000, interval = 1000) { - setTimeout(function() { - setInterval(function() { - const currentLog = apbctLocalStorage.get('ct_bot_detector_frontend_data_log'); - if (needsSaveLogToAltSessions(currentLog)) { - botDetectorLogLastUpdate = currentLog.log_last_update; - // the log will be taken from javascriptclientdata - ctSetAlternativeCookie([], {forceAltCookies: true}); - } - }, interval); - }, cronStartTimeout); -} +class ApbctBrowserState { + static STATE_KEY = 'apbct_browser_state'; + static LOG_KEY = 'ct_bot_detector_frontend_data_log'; + static SCRIPT_SIGNS = { + botd_wrapper_loaded: 'ct-bot-detector-wrapper', + botd_logic_loaded: 'ct-bot-detector.min', + }; + /** + * This LS key is set on bot-detector side + * @type {string} + */ + static TRANSPORT_ENABLED_SIGN_KEY = 'bot_detector_log_transport_enabled'; + static botdWrapperLoaded = 0; + static botdLogicLoaded = 0; -/** - * Check if the log needs to be saved to the alt sessions. If the log has new event types, it will be saved. - * @param {object} currentLog - * @return {boolean} - */ -function needsSaveLogToAltSessions(currentLog) { - if ( - currentLog && currentLog.hasOwnProperty('log_last_update') && - botDetectorLogLastUpdate !== currentLog.log_last_update - ) { - try { - for (let i = 0; i < currentLog.records.length; i++) { - const currentType = currentLog.records[i].frontend_data.js_event; - // check if this event type was already collected - if (currentType !== undefined && botDetectorLogEventTypesCollected.includes(currentType)) { - continue; + /** + * Get the current browser state as a JSON string ready to be transferred. + * @return {string} Empty string if the bot detector is disabled or on any collecting error. + */ + static getFrontendDataLog() { + const prefix = (typeof ctPublicFunctions !== 'undefined' && ctPublicFunctions.cookiePrefix) ? + ctPublicFunctions.cookiePrefix : + ''; + const logKey = prefix + ApbctBrowserState.LOG_KEY; + const noPrefixLogKey = ApbctBrowserState.LOG_KEY; + + if (typeof apbctLocalStorage !== 'undefined' && apbctLocalStorage.get) { + const logObject = apbctLocalStorage.get(logKey) || apbctLocalStorage.get(noPrefixLogKey) || null; + if (logObject && typeof logObject === 'string') { + try { + return JSON.parse(logObject); + } catch (e) { + return ''; } - // add new event type to collection, this type will be sent to the alt sessions further - botDetectorLogEventTypesCollected.push(currentType); - return true; } + return logObject; + } + + let rawLog = localStorage.getItem(logKey); + if (!rawLog) { + rawLog = localStorage.getItem(noPrefixLogKey) || null; + } + + try { + return typeof rawLog === 'string' ? JSON.parse(rawLog) : rawLog; } catch (e) { - console.log('APBCT: bot detector log collection error: ' . e.toString()); + return ''; } } - return false; -} + /** + * + * @return {object} + */ + static asDTO() { + return { + botd_logic_loaded: ApbctBrowserState.botdLogicLoaded, + botd_wrapper_loaded: ApbctBrowserState.botdWrapperLoaded, + frontend_data_log: '', + transport_enabled: 1, + }; + } + + /** + * Look for the bot detector scripts in the page DOM. + * @return {boolean} True if both scripts are found. + */ + static detectScripts() { + if (ApbctBrowserState.botdWrapperLoaded && ApbctBrowserState.botdLogicLoaded) { + return true; + } + + const scripts = document.getElementsByTagName('script'); + + for (let i = 0; i < scripts.length; i++) { + const src = scripts[i].getAttribute('src'); + if (!src) { + continue; + } + if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_wrapper_loaded) !== -1) { + ApbctBrowserState.botdWrapperLoaded = 1; + } else if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_logic_loaded) !== -1) { + ApbctBrowserState.botdLogicLoaded = 1; + } + } + + // The bot detector logic sets this flag on its own start + return !!ApbctBrowserState.botdWrapperLoaded && !!ApbctBrowserState.botdLogicLoaded; + } +} +/** + * Get the browser state as a key/value pair to attach it to an intercepted request. + * @return {{key: string, value: string}|false} False if there is nothing to attach. + */ +function apbctGetBrowserStatePair() { // eslint-disable-line no-unused-vars + try { + ApbctBrowserState.detectScripts(); + let state = ApbctBrowserState.asDTO(); + if ( ApbctBrowserState.botdLogicLoaded ) { + const transportEnabled = localStorage.getItem(ApbctBrowserState.TRANSPORT_ENABLED_SIGN_KEY) === '1'; + if (transportEnabled) { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } else { + state.transport_enabled = 0; + } + } else { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } + return {key: ApbctBrowserState.STATE_KEY, value: JSON.stringify(state)}; + } catch (e) { + return false; + } +} let ctCheckedEmails = {}; let ctCheckedEmailsExist = {}; diff --git a/js/prebuild/apbct-public-bundle_int-protection.js b/js/prebuild/apbct-public-bundle_int-protection.js index 33c495707..1eac108d8 100644 --- a/js/prebuild/apbct-public-bundle_int-protection.js +++ b/js/prebuild/apbct-public-bundle_int-protection.js @@ -2253,7 +2253,7 @@ function ctSetCookie( cookies, value, expires='') { let listOfCookieNamesToForceAlt = [ 'ct_sfw_pass_key', 'ct_sfw_passed', - 'wordpress_apbct_antibot', + 'apbct_antibot', 'apbct_anticrawler_passed', 'apbct_bot_detector_exist', 'apbct_antiflood_passed', @@ -2642,6 +2642,15 @@ function getNoCookieData() { // eslint-disable-line no-unused-vars let noCookieDataLocal = apbctLocalStorage.getCleanTalkData(); let noCookieDataSession = apbctSessionStorage.getCleanTalkData(); let noCookieData = {...noCookieDataLocal, ...noCookieDataSession}; + + // Bot detector browser state is transferred with the hidden field on the NoCookie mode + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + noCookieData[browserState.key] = browserState.value; + } + } + noCookieData = JSON.stringify(noCookieData); return '_ct_no_cookie_data_' + btoa(unescape(encodeURIComponent(noCookieData))); @@ -2669,7 +2678,21 @@ function getCleanTalkStorageDataArray() { // eslint-disable-line no-unused-vars noCookieDataFromUserActivity = {collecting_user_activity_data: collectingUserActivityData}; } - return {...noCookieDataLocal, ...noCookieDataSession, ...noCookieDataTypo, ...noCookieDataFromUserActivity}; + let browserStateData = {}; + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + browserStateData[browserState.key] = browserState.value; + } + } + + return { + ...noCookieDataLocal, + ...noCookieDataSession, + ...noCookieDataTypo, + ...noCookieDataFromUserActivity, + ...browserStateData, + }; } /** @@ -3314,6 +3337,9 @@ class ApbctHandler { const eventTokenKey = useUnwrappedCleantalkKeys ? 'ct_bot_detector_event_token' : 'data%5Bct_bot_detector_event_token%5D'; + const browserStateKey = useUnwrappedCleantalkKeys ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; if (!( +ctPublic.bot_detector_enabled && @@ -3338,6 +3364,12 @@ class ApbctHandler { } } + const browserState = apbctGetBrowserStatePair(); + if (browserState && body.indexOf('apbct_browser_state') === -1) { + addidionalCleantalkData += '&' + browserStateKey + '=' + + encodeURIComponent(browserState.value); + } + body += addidionalCleantalkData; } @@ -3354,6 +3386,11 @@ class ApbctHandler { body.append('ct_bot_detector_event_token', eventToken); } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState && !body.has(browserState.key)) { + body.append(browserState.key, browserState.value); + } } if (isNeedToAddCleantalkDataCheckJsonData) { @@ -3391,6 +3428,22 @@ class ApbctHandler { } } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + try { + const bodyObj = JSON.parse(body); + if ( + bodyObj && typeof bodyObj === 'object' && + !Object.prototype.hasOwnProperty.call(bodyObj, browserState.key) + ) { + bodyObj[browserState.key] = browserState.value; + body = JSON.stringify(bodyObj); + } + } catch (e) { + // body is not JSON — leave as is + } + } } return originalSend.apply(this, [body]); @@ -3448,6 +3501,11 @@ class ApbctHandler { } else { args[1].body.append('ct_no_cookie_hidden_field', getNoCookieData()); } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + args[1].body.append(browserState.key, browserState.value); + } } } } catch (e) { @@ -3504,6 +3562,22 @@ class ApbctHandler { * @return {string|FormData} Modified body. */ const attachFieldsToBody = function(body, fieldPair = false) { + const fieldPairs = [fieldPair, apbctGetBrowserStatePair()]; + + for (const pair of fieldPairs) { + body = attachFieldPairToBody(body, pair); + } + + return body; + }; + + /** + * Attach a single key/value pair to fetch request body + * @param {string|FormData} body Fetch request data body. + * @param {object|bool} fieldPair Key value to inject. + * @return {string|FormData} Modified body. + */ + const attachFieldPairToBody = function(body, fieldPair = false) { if (fieldPair) { if (body instanceof FormData || typeof body.append === 'function') { body.append(fieldPair.key, fieldPair.value); @@ -3800,11 +3874,15 @@ class ApbctHandler { const batchPayload = JSON.parse(args[1].body); if (batchPayload.requests && Array.isArray(batchPayload.requests)) { const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); + const browserState = apbctGetBrowserStatePair(); for (const req of batchPayload.requests) { const isAddItem = req.path === '/wc/store/v1/cart/add-item'; if (isAddItem && req.body && fieldPair && fieldPair.key) { req.body[fieldPair.key] = fieldPair.value; } + if (isAddItem && req.body && browserState) { + req.body[browserState.key] = browserState.value; + } } args[1].body = JSON.stringify(batchPayload); } @@ -3828,289 +3906,1086 @@ class ApbctHandler { } /** - * Prepare jQuery.ajaxSetup to add nocookie data to the jQuery ajax request. + * Prepare jQuery.ajaxPrefilter to add CleanTalk data to jQuery ajax requests. * Notes: - * - Do it just once, the ajaxSetup.beforeSend will be overwritten for any calls. - * - Signs of forms need to be caught will be checked during ajaxSetup.settings.data process on send. + * - ajaxSetup.beforeSend is not used: a request can supply its own beforeSend and drop the default. + * - ajaxPrefilter runs for every jQuery ajax call after options are merged, so injection is guaranteed. + * - Form signs are checked on the request data/url at send time. * - Any sign of the form HTML of the caller is insignificant in this process. * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script * will work independing if jQuery is loaded by CleanTalk or not * @return {void} */ catchJqueryAjax() { - if ( typeof jQuery !== 'undefined') { - // this code run on base ajax rules - so do not work due scripts use it's own ajax object injections - if ( typeof jQuery.ajaxSetup === 'function' ) { - jQuery.ajaxSetup({ - beforeSend: function(xhr, settings) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(settings, 'ajaxSetup'); - if (sourceSign.found !== false) { - settings.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, settings.data); - } - }, - }); - } - // this code run on ANY ajax on ANY script queue status - // todo Probably move all ajaxSetup actions to ajaxPrefilter - if ( typeof jQuery.ajaxPrefilter === 'function' ) { - jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(options, 'ajaxPrefilter'); - if (sourceSign.found !== false) { - if (typeof options.data === 'string') { - options.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, options.data); - } - if ( - typeof options.data === 'object' && - typeof options.data.append === 'function' - ) { - options.data = handler.injectCleantalkDataToJQAjaxFormData(sourceSign, options.data); - } - } - }); - } + if ( typeof jQuery !== 'undefined' && typeof jQuery.ajaxPrefilter === 'function' ) { + jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { + const handler = new ApbctHandler(); + const sourceSign = handler.searchSignsForJQAjaxInjection(options, originalOptions); + if (sourceSign.found !== false) { + options.data = handler.injectCleantalkDataToJQAjax( + sourceSign, + handler.getJQAjaxPayloadForInject(options, originalOptions), + options, + ); + } + }); } } /** - * Search for sign within AJAX data to do inject CleanTalk data. - * @param {object} ajaxObject Ajax object. - * @param {string} catchOn Function should be catched on. - * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + * jQuery.param() on URLSearchParams/FormData can collapse options.data to "". + * Sign search already falls back to originalOptions; inject must use that payload too. + * @param {object} options + * @param {object=} originalOptions + * @return {*} */ - searchSignsForJQAjaxInjection(ajaxObject, catchOn = 'ajaxSetup') { - let sourceSign = { - 'found': false, - 'keepUnwrapped': false, - 'attachVisibleFieldsData': false, - }; - // on ajaxSetup - if (catchOn === 'ajaxSetup') { - // settings data is string (important!) - if ( typeof ajaxObject.data === 'string' ) { - if ( - ajaxObject.data.indexOf('action=fl_builder_subscribe_form_submit') !== -1 - ) { - sourceSign.found = 'fl_builder_subscribe_form_submit'; - } - if ( - ajaxObject.data.indexOf('twt_cc_signup') !== -1 - ) { - sourceSign.found = 'twt_cc_signup'; - } - if ( - ajaxObject.data.indexOf('action=mailpoet') !== -1 - ) { - sourceSign.found = 'action=mailpoet'; - sourceSign.attachVisibleFieldsData = true; - } - - if ( - ajaxObject.data.indexOf('action=user_registration') !== -1 && - ajaxObject.data.indexOf('ur_frontend_form_nonce') !== -1 - ) { - sourceSign.found = 'action=user_registration'; - } - - if (ajaxObject.data.indexOf('action=happyforms_message') !== -1) { - sourceSign.found = 'action=happyforms_message'; - } - - if ( - ajaxObject.data.indexOf('action=new_activity_comment') !== -1 - ) { - sourceSign.found = 'action=new_activity_comment'; - } - if ( - ajaxObject.data.indexOf('action=wwlc_create_user') !== -1 - ) { - sourceSign.found = 'action=wwlc_create_user'; - } - if ( - ajaxObject.data.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 - ) { - sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=drplus_signup') !== -1 - ) { - sourceSign.found = 'action=drplus_signup'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=bt_cc') !== -1 - ) { - sourceSign.found = 'action=bt_cc'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=wpr_form_builder_email') !== -1 - ) { - sourceSign.found = 'action=wpr_form_builder_email'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=nf_ajax_submit') !== -1 - ) { - sourceSign.found = 'action=nf_ajax_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=uael_register_user') !== -1 && - ctPublic.data__cookies_type === 'none' - ) { - sourceSign.found = 'action=uael_register_user'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=SQBSubmitQuizAjax') !== -1 - ) { - sourceSign.found = 'action=SQBSubmitQuizAjax'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=user_registration_user_form_submit') !== -1 - ) { - sourceSign.found = 'action=user_registration_user_form_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - } - // wooocommerce add to cart is based on URL - if ( typeof ajaxObject.url === 'string' ) { - if (ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1) { - sourceSign.found = 'wc-ajax=add_to_cart'; - } - } + getJQAjaxPayloadForInject(options, originalOptions) { + const current = options && options.data; + const original = originalOptions && originalOptions.data; + if ( this.jqAjaxPayloadWasCollapsed(current, original) ) { + return original; } + return current; + } - // on ajaxPrefilter - if (catchOn === 'ajaxPrefilter') { - if (typeof ajaxObject.data === 'string') { - if (ajaxObject.data.indexOf('action=bloom_subscribe') !== -1) { - sourceSign.found = 'action=bloom_subscribe'; - sourceSign.keepUnwrapped = true; - } - } + /** + * @param {*} current + * @param {*} original + * @return {boolean} + */ + jqAjaxPayloadWasCollapsed(current, original) { + if ( original === null || typeof original === 'undefined' ) { + return false; + } + if ( current === original ) { + return false; + } + const currentEmpty = current === '' || current === null || typeof current === 'undefined'; + if ( !currentEmpty ) { + return false; + } + if ( typeof original === 'string' ) { + return original !== ''; + } + return this.isJQAjaxFormData(original) || + this.isJQAjaxURLSearchParams(original) || + this.isJQAjaxPlainObjectOrArray(original); + } - if ( - typeof ajaxObject.data === 'object' && - ajaxObject.data !== null && - typeof ajaxObject.data.get === 'function' - ) { - if (ajaxObject.data.get('action') === 'pafe_ajax_form_builder') { - sourceSign.found = 'action=pafe_ajax_form_builder'; - sourceSign.keepUnwrapped = true; - } - } + /** + * Normalize jQuery ajax data to a query string for sign search. + * Objects and serializeArray are read structurally so search never calls jQuery.param. + * Also reads known sign fields from the URL (IE11 FormData cannot be enumerated). + * @param {object} ajaxObject Ajax options object. + * @return {string} + */ + getJQAjaxDataAsString(ajaxObject) { + if ( !ajaxObject || typeof ajaxObject !== 'object' ) { + return ''; + } + let fromData = ''; + if ( typeof ajaxObject.data === 'string' ) { + fromData = ajaxObject.data; + } else if ( this.isJQAjaxPlainObjectOrArray(ajaxObject.data) ) { + fromData = this.getStructuredJQAjaxSignString(ajaxObject.data); + } else if ( this.isJQAjaxURLSearchParams(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } else if ( this.isJQAjaxFormData(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } + // Native IE11 FormData is write-only (no get/forEach/entries). Signs then come from the URL. + const fromUrl = this.collectKnownSignStringFromUrl(ajaxObject.url); + if ( fromData && fromUrl ) { + return fromData + '&' + fromUrl; } + return fromData || fromUrl; + } - return sourceSign; + /** + * Build a sign string from top-level fields without serializing the whole payload. + * @param {object|Array} data + * @return {string} + */ + getStructuredJQAjaxSignString(data) { + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return this.getSerializeArraySignString(data); + } + const parts = []; + const action = this.getPlainObjectSignField(data, 'action'); + if ( typeof action === 'string' && action !== '' ) { + parts.push('action=' + action); + } + const nonce = this.getPlainObjectSignField(data, 'ur_frontend_form_nonce'); + if ( nonce !== null ) { + parts.push('ur_frontend_form_nonce=' + nonce); + } + if ( this.plainObjectHasTwtCcSignup(data) ) { + parts.push('twt_cc_signup=1'); + } + return parts.join('&'); } /** - * Injecting CleanTalk data to ajax data FormData object. - * @param {object} sourceSign - * @param {object} ajaxDataFormData - * @return {object} + * Read action/nonce from top-level, data[key], or nested data.key. + * @param {object} data + * @param {string} key + * @return {string|number|null} */ - injectCleantalkDataToJQAjaxFormData(sourceSign, ajaxDataFormData) { + getPlainObjectSignField(data, key) { + if ( !data || typeof data !== 'object' ) { + return null; + } + if ( this.isJQAjaxScalarSignValue(data[key]) ) { + return data[key]; + } + const bracketKey = 'data[' + key + ']'; + if ( this.isJQAjaxScalarSignValue(data[bracketKey]) ) { + return data[bracketKey]; + } if ( - typeof sourceSign !== 'object' || - typeof ajaxDataFormData !== 'object' || - !(ajaxDataFormData instanceof FormData) + data.data && + typeof data.data === 'object' && + Object.prototype.toString.call(data.data) !== '[object Array]' && + this.isJQAjaxScalarSignValue(data.data[key]) ) { - return ajaxDataFormData; + return data.data[key]; } + return null; + } - try { - // Event token + /** + * @param {*} value + * @return {boolean} + */ + isJQAjaxScalarSignValue(value) { + return typeof value === 'string' || typeof value === 'number'; + } + + /** + * @param {object} data + * @param {number=} depth + * @return {boolean} + */ + plainObjectHasTwtCcSignup(data, depth) { + if ( !data || typeof data !== 'object' ) { + return false; + } + if ( typeof depth === 'undefined' ) { + depth = 0; + } + if ( depth > 2 ) { + return false; + } + for ( const key in data ) { + if ( !Object.prototype.hasOwnProperty.call(data, key) ) { + continue; + } + const normalizedKey = this.unwrapJQAjaxFormDataKey(key); + if ( normalizedKey === 'twt_cc_signup' || key.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + const value = data[key]; + if ( typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1 ) { + return true; + } if ( - +ctPublic.bot_detector_enabled && - apbctLocalStorage.get('bot_detector_event_token') + value && + typeof value === 'object' && + Object.prototype.toString.call(value) !== '[object Array]' ) { - const token = this.toolGetEventToken(); - if (token) { - if (sourceSign.keepUnwrapped) { - ajaxDataFormData.append('ct_bot_detector_event_token', token); - } else { - ajaxDataFormData.append('data[ct_bot_detector_event_token]', token); - } - } - } else { - // No cookie data - let noCookieData = getNoCookieData(); - if (noCookieData) { - if (sourceSign.keepUnwrapped) { - ajaxDataFormData.append('ct_no_cookie_hidden_field', noCookieData); - } else { - ajaxDataFormData.append('data[ct_no_cookie_hidden_field]', noCookieData); - } + if ( this.plainObjectHasTwtCcSignup(value, depth + 1) ) { + return true; } } + } + return false; + } - // Visible fields - if (sourceSign.attachVisibleFieldsData) { - let visibleFieldsSearchResult = false; - const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); - if (extractor) { - // Try to find form_id in FormData to find form container and - // collect visible fields only inside it - let formId = null; - for (let pair of ajaxDataFormData.entries()) { - if (pair[0] === 'form_id' || pair[0] === 'data[form_id]') { - formId = pair[1]; - break; - } - } - let container = null; - if (formId && typeof formId === 'string') { - // Sanitize formId to prevent selector injection - const sanitizedFormId = formId.replace(/["\\]/g, ''); - // First, try to find by id - container = document.getElementById(sanitizedFormId); - // If not found, try to find by data-id - if (!container) { - container = document.querySelector('[data-id="' + sanitizedFormId + '"]'); - } - } - if (container) { - // Collect all input, select, textarea inside the container - const fields = container.querySelectorAll('input, select, textarea'); - // Use collectVisibleFields, passing an object with elements - const visibleFieldsObj = new ApbctAttachData().collectVisibleFields({elements: fields}); - visibleFieldsSearchResult = JSON.stringify(visibleFieldsObj); - } - } - if (typeof visibleFieldsSearchResult === 'string' && visibleFieldsSearchResult.length > 0) { - ajaxDataFormData.append('apbct_visible_fields', visibleFieldsSearchResult); - } + /** + * @param {Array} entries + * @return {string} + */ + getSerializeArraySignString(entries) { + const parts = []; + for ( let i = 0; i < entries.length; i++ ) { + const entry = entries[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + continue; + } + const value = entry.value; + const normalizedKey = this.unwrapJQAjaxFormDataKey(entry.name); + if ( this.isJQAjaxKnownSignField(normalizedKey, value) ) { + parts.push(normalizedKey + '=' + value); } - } catch (e) { - // Silently fail to not break the original request } - - return ajaxDataFormData; + return parts.join('&'); } /** - * Injecting CleanTalk data to ajax data string. - * @param {object} sourceSign Object of found sign to intercept. - * @param {string} ajaxDataString Original data string from ajax object. - * @return {string} + * True for serializeArray payloads, including an empty array. + * @param {Array} data + * @return {boolean} */ - injectCleantalkDataToJQAjaxString(sourceSign, ajaxDataString) { - // something wrong with incoming data - if (typeof sourceSign !== 'object' || typeof ajaxDataString !== 'string') { - return ajaxDataString; + isJQAjaxSerializeArray(data) { + if ( Object.prototype.toString.call(data) !== '[object Array]' ) { + return false; + } + for ( let i = 0; i < data.length; i++ ) { + const entry = data[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + return false; + } + } + return true; + } + + /** + * Cross-realm URLSearchParams (instanceof fails across windows). + * @param {*} data + * @return {boolean} + */ + isJQAjaxURLSearchParams(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object URLSearchParams]' ) { + return true; + } + if ( tag === '[object FormData]' ) { + return false; + } + return typeof data.sort === 'function' && typeof data.get === 'function'; + } + + /** + * Cross-realm FormData, including common polyfills. + * @param {*} data + * @return {boolean} + */ + isJQAjaxFormData(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) || this.isJQAjaxURLSearchParams(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object FormData]' ) { + return true; + } + if ( tag === '[object Headers]' || typeof data.getSetCookie === 'function' ) { + return false; + } + return typeof data.forEach === 'function' || + typeof data.get === 'function' || + typeof data.entries === 'function'; + } + + /** + * Collect only known sign fields from FormData / URLSearchParams. + * Unwrap data[action] so later action=... checks match. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + collectKnownSignStringFromKeyValueBag(bag) { + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' ) { + return; + } + const valueAsString = String(value); + const normalizedKey = unwrapKey(key); + if ( + knownKeys[normalizedKey] || + valueAsString.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + valueAsString); + } + }); + if ( collected ) { + return parts.join('&'); + } + if ( typeof bag.get !== 'function' ) { + return ''; + } + const keysToProbe = [ + 'action', + 'ur_frontend_form_nonce', + 'twt_cc_signup', + ]; + const getParts = []; + for ( let i = 0; i < keysToProbe.length; i++ ) { + const key = keysToProbe[i]; + const value = this.getFormDataScalarValue(bag, [key, 'data[' + key + ']']); + if ( value !== null ) { + getParts.push(key + '=' + value); + } + } + return getParts.join('&'); + } + + /** + * Known sign fields from a request URL query. IE11-safe (no URLSearchParams). + * @param {string} url + * @return {string} + */ + collectKnownSignStringFromUrl(url) { + if ( typeof url !== 'string' || url === '' ) { + return ''; + } + const queryIndex = url.indexOf('?'); + if ( queryIndex === -1 || queryIndex === url.length - 1 ) { + return ''; + } + const hashIndex = url.indexOf('#', queryIndex); + const query = hashIndex === -1 ? + url.slice(queryIndex + 1) : + url.slice(queryIndex + 1, hashIndex); + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const pairs = query.split('&'); + for ( let i = 0; i < pairs.length; i++ ) { + const pair = pairs[i]; + if ( !pair ) { + continue; + } + const eq = pair.indexOf('='); + let rawKey = eq === -1 ? pair : pair.slice(0, eq); + let rawValue = eq === -1 ? '' : pair.slice(eq + 1); + try { + rawKey = decodeURIComponent(rawKey.replace(/\+/g, ' ')); + rawValue = decodeURIComponent(rawValue.replace(/\+/g, ' ')); + } catch (e) { + continue; + } + const normalizedKey = unwrapKey(rawKey); + if ( + knownKeys[normalizedKey] || + rawValue.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + rawValue); + } + } + return parts.join('&'); + } + + /** + * Walk FormData/URLSearchParams via forEach, then entries() for polyfills that only have an iterator. + * @param {FormData|URLSearchParams} bag + * @param {Function} callback + * @return {boolean} + */ + forEachJQAjaxKeyValueBag(bag, callback) { + if ( typeof bag.forEach === 'function' ) { + try { + bag.forEach(callback); + return true; + } catch (e) { + // Fall through to entries(). + } + } + if ( typeof bag.entries !== 'function' ) { + return false; + } + try { + const iterator = bag.entries(); + if ( !iterator || typeof iterator.next !== 'function' ) { + return false; + } + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + callback(pair[1], pair[0]); + } + step = iterator.next(); + } + return true; + } catch (e) { + return false; + } + } + + /** + * @return {Object} + */ + getJQAjaxKnownSignKeys() { + const knownKeys = Object.create(null); + knownKeys.action = true; + knownKeys.ur_frontend_form_nonce = true; + knownKeys.twt_cc_signup = true; + return knownKeys; + } + + /** + * @param {string} normalizedKey + * @param {*} value + * @return {boolean} + */ + isJQAjaxKnownSignField(normalizedKey, value) { + if ( + normalizedKey === 'action' || + normalizedKey === 'ur_frontend_form_nonce' || + normalizedKey === 'twt_cc_signup' || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + return true; + } + return typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1; + } + + /** + * Treat data[action] as action for WP-style payloads. + * @param {string} key + * @return {string} + */ + unwrapJQAjaxFormDataKey(key) { + if ( typeof key !== 'string' ) { + return ''; + } + if ( key.length > 6 && key.indexOf('data[') === 0 && key.charAt(key.length - 1) === ']' ) { + return key.slice(5, -1); + } + return key; + } + + /** + * @param {FormData} formData + * @param {Array.} keys + * @return {string|number|null} + */ + getFormDataScalarValue(formData, keys) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && (typeof value === 'string' || typeof value === 'number') ) { + return value; + } + } + return null; + } + + /** + * True for arrays and plain objects that jQuery.param can serialize safely. + * @param {*} data + * @return {boolean} + */ + isJQAjaxPlainObjectOrArray(data) { + if ( data === null || typeof data !== 'object' ) { + return false; + } + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return true; + } + if ( typeof jQuery !== 'undefined' && typeof jQuery.isPlainObject === 'function' ) { + return jQuery.isPlainObject(data); + } + const proto = Object.getPrototypeOf(data); + return proto === Object.prototype || proto === null; + } + + /** + * Search for sign within AJAX data to do inject CleanTalk data. + * @param {object} ajaxObject Ajax object. + * @param {object=} originalOptions Original jQuery ajax options before merge. + * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + */ + searchSignsForJQAjaxInjection(ajaxObject, originalOptions) { + let sourceSign = { + 'found': false, + 'keepUnwrapped': false, + 'attachVisibleFieldsData': false, + }; + let dataString = this.getJQAjaxDataAsString(ajaxObject); + if ( !dataString && originalOptions && originalOptions !== ajaxObject ) { + dataString = this.getJQAjaxDataAsString(originalOptions); + } + + if ( dataString.indexOf('action=fl_builder_subscribe_form_submit') !== -1 ) { + sourceSign.found = 'fl_builder_subscribe_form_submit'; + } + if ( dataString.indexOf('twt_cc_signup') !== -1 ) { + sourceSign.found = 'twt_cc_signup'; + } + if ( dataString.indexOf('action=mailpoet') !== -1 ) { + sourceSign.found = 'action=mailpoet'; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=user_registration') !== -1 && + dataString.indexOf('ur_frontend_form_nonce') !== -1 + ) { + sourceSign.found = 'action=user_registration'; + } + if ( dataString.indexOf('action=happyforms_message') !== -1 ) { + sourceSign.found = 'action=happyforms_message'; + } + if ( dataString.indexOf('action=new_activity_comment') !== -1 ) { + sourceSign.found = 'action=new_activity_comment'; + } + if ( dataString.indexOf('action=wwlc_create_user') !== -1 ) { + sourceSign.found = 'action=wwlc_create_user'; + } + if ( dataString.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 ) { + sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=drplus_signup') !== -1 ) { + sourceSign.found = 'action=drplus_signup'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=bt_cc') !== -1 ) { + sourceSign.found = 'action=bt_cc'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=wpr_form_builder_email') !== -1 ) { + sourceSign.found = 'action=wpr_form_builder_email'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=nf_ajax_submit') !== -1 ) { + sourceSign.found = 'action=nf_ajax_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=uael_register_user') !== -1 && + ctPublic.data__cookies_type === 'none' + ) { + sourceSign.found = 'action=uael_register_user'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=SQBSubmitQuizAjax') !== -1 ) { + sourceSign.found = 'action=SQBSubmitQuizAjax'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=user_registration_user_form_submit') !== -1 ) { + sourceSign.found = 'action=user_registration_user_form_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=bloom_subscribe') !== -1 ) { + sourceSign.found = 'action=bloom_subscribe'; + sourceSign.keepUnwrapped = true; + } + if ( + this.isJQAjaxFormData(ajaxObject.data) && + typeof ajaxObject.data.get === 'function' && + ajaxObject.data.get('action') === 'pafe_ajax_form_builder' + ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } else if ( dataString.indexOf('action=pafe_ajax_form_builder') !== -1 ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } + + // woocommerce add to cart is based on URL + if ( typeof ajaxObject.url === 'string' && ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1 ) { + sourceSign.found = 'wc-ajax=add_to_cart'; + // GET/HEAD: PHP reads Get::get('ct_bot_detector_event_token'), not data[...]. + if ( this.isJQAjaxNoContentMethod(ajaxObject) ) { + sourceSign.keepUnwrapped = true; + } + } + + return sourceSign; + } + + /** + * Inject CleanTalk data into jQuery ajax payload of any supported type. + * @param {object} sourceSign + * @param {*} ajaxData + * @param {object=} ajaxOptions jQuery ajax options (traditional, processData, contentType). + * Keep URLSearchParams/objects when processData or contentType is false. + * URLSearchParams must also disable processData, or jQuery.param() later yields "". + * GET/HEAD never keep the original type: jQuery only puts string data on the URL. + * @return {*} + */ + injectCleantalkDataToJQAjax(sourceSign, ajaxData, ajaxOptions) { + const traditional = ajaxOptions && ajaxOptions.traditional; + const keepOriginalType = !this.isJQAjaxNoContentMethod(ajaxOptions) && !!(ajaxOptions && ( + ajaxOptions.processData === false || + ajaxOptions.contentType === false + )); + + if ( ajaxData === null || typeof ajaxData === 'undefined' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ''); + } + if ( typeof ajaxData === 'string' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData); + } + if ( this.isJQAjaxPlainObjectOrArray(ajaxData) ) { + if ( keepOriginalType ) { + if ( Object.prototype.toString.call(ajaxData) === '[object Array]' ) { + if ( this.isJQAjaxSerializeArray(ajaxData) ) { + return this.injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData); + } + return ajaxData; + } + return this.injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData); + } + try { + if ( typeof jQuery !== 'undefined' && typeof jQuery.param === 'function' ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + jQuery.param(ajaxData, traditional), + ); + } + } catch (e) { + return ajaxData; + } + return ajaxData; + } + if ( this.isJQAjaxURLSearchParams(ajaxData) ) { + if ( keepOriginalType ) { + this.preserveJQAjaxURLSearchParamsOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxKeyValue( + sourceSign, + this.cloneURLSearchParams(ajaxData), + ); + } + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData.toString()); + } + if ( this.isJQAjaxFormData(ajaxData) ) { + if ( this.isJQAjaxNoContentMethod(ajaxOptions) ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + this.serializeJQAjaxKeyValueBag(ajaxData), + ); + } + this.preserveJQAjaxFormDataOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxFormData( + sourceSign, + this.cloneFormData(ajaxData), + ); + } + return ajaxData; + } + + /** + * GET/HEAD have no body. Missing type is GET (jQuery default). + * @param {object=} ajaxOptions + * @return {boolean} + */ + isJQAjaxNoContentMethod(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return false; + } + const type = ajaxOptions.type || ajaxOptions.method; + if ( typeof type !== 'string' || type === '' ) { + return true; + } + const method = type.toUpperCase(); + return method === 'GET' || method === 'HEAD'; + } + + /** + * Collect CleanTalk fields to append to a key/value payload. + * @param {object} sourceSign + * @return {Array.>} + */ + getCleantalkJQAjaxFieldPairs(sourceSign) { + const pairs = []; + const wrapKey = function(key) { + return sourceSign.keepUnwrapped ? key : 'data[' + key + ']'; + }; + + if ( + +ctPublic.bot_detector_enabled && + apbctLocalStorage.get('bot_detector_event_token') + ) { + const token = this.toolGetEventToken(); + if ( token ) { + pairs.push([wrapKey('ct_bot_detector_event_token'), token]); + } + } else { + const noCookieData = getNoCookieData(); + if ( noCookieData ) { + pairs.push([wrapKey('ct_no_cookie_hidden_field'), noCookieData]); + } + } + + const browserState = apbctGetBrowserStatePair(); + if ( browserState ) { + const browserStateKey = sourceSign.keepUnwrapped ? + browserState.key : + 'data[' + browserState.key + ']'; + pairs.push([browserStateKey, browserState.value]); + } + + return pairs; + } + + /** + * jQuery.param(FormData) after the prefilter yields "". Keep the body as FormData. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxFormDataOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + ajaxOptions.contentType = false; + } + + /** + * jQuery.param(URLSearchParams) after the prefilter yields "". Keep the body as URLSearchParams. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxURLSearchParamsOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + } + + /** + * Read a FormData field via get(), forEach(), or entries(). + * Native IE11 FormData is write-only and cannot be read. + * @param {FormData} formData + * @param {Array.} keys + * @return {*} + */ + getFormDataField(formData, keys) { + if ( typeof formData.get === 'function' ) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && typeof value !== 'undefined' ) { + return value; + } + } + } + if ( typeof formData.forEach === 'function' ) { + let found = null; + formData.forEach(function(value, key) { + if ( found !== null ) { + return; + } + for ( let i = 0; i < keys.length; i++ ) { + if ( key === keys[i] ) { + found = value; + return; + } + } + }); + if ( found !== null ) { + return found; + } + } + if ( typeof formData.entries === 'function' ) { + try { + const iterator = formData.entries(); + if ( iterator && typeof iterator.next === 'function' ) { + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + for ( let i = 0; i < keys.length; i++ ) { + if ( pair[0] === keys[i] ) { + return pair[1]; + } + } + } + step = iterator.next(); + } + } + } catch (e) { + return null; + } + } + return null; + } + + /** + * Clone URLSearchParams so the caller's instance is not mutated. + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + cloneURLSearchParams(params) { + const serialized = typeof params.toString === 'function' ? params.toString() : ''; + if ( typeof params.constructor === 'function' && params.constructor !== Object ) { + try { + return new params.constructor(serialized); + } catch (e) { + // Fall through to the current-window constructor. + } + } + if ( typeof URLSearchParams === 'function' ) { + try { + return new URLSearchParams(serialized); + } catch (e) { + return params; + } + } + return params; + } + + /** + * Clone FormData when it can be enumerated (forEach or entries); otherwise reuse. + * @param {FormData} formData + * @return {FormData} + */ + cloneFormData(formData) { + try { + const clone = new FormData(); + const copied = this.forEachJQAjaxKeyValueBag(formData, function(value, key) { + clone.append(key, value); + }); + if ( copied ) { + return clone; + } + } catch (e) { + return formData; + } + return formData; + } + + /** + * Form-urlencoded string from FormData/URLSearchParams. Skip File/Blob values. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + serializeJQAjaxKeyValueBag(bag) { + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { + return; + } + parts.push(encodeURIComponent(String(key)) + '=' + encodeURIComponent(String(value))); + }); + if ( collected ) { + return parts.join('&'); + } + return ''; + } + + /** + * Inject CleanTalk fields into URLSearchParams without changing the payload type. + * @param {object} sourceSign + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + injectCleantalkDataToJQAjaxKeyValue(sourceSign, params) { + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + params.append(pairs[i][0], pairs[i][1]); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( extractor ) { + const extracted = extractor.extract(params.toString()); + if ( typeof extracted === 'string' ) { + params.append('apbct_visible_fields', extracted); + } + } + } + return params; + } + + /** + * Inject CleanTalk fields into a jQuery serializeArray payload. + * @param {object} sourceSign + * @param {Array} ajaxData + * @return {Array} + */ + injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData) { + const result = ajaxData.slice(); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result.push({ + name: pairs[i][0], + value: pairs[i][1], + }); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' + ) { + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.push({ + name: 'apbct_visible_fields', + value: extracted, + }); + } + } + } + return result; + } + + /** + * Inject CleanTalk fields into a plain object without changing the payload type. + * @param {object} sourceSign + * @param {object} ajaxData + * @return {object} + */ + injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData) { + const result = typeof jQuery !== 'undefined' && typeof jQuery.extend === 'function' ? + jQuery.extend({}, ajaxData) : + this.clonePlainObject(ajaxData); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result[pairs[i][0]] = pairs[i][1]; + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' + ) { + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.apbct_visible_fields = extracted; + } + } + } + return result; + } + + /** + * IE11-safe shallow copy of a plain object. + * @param {object} ajaxData + * @return {object} + */ + clonePlainObject(ajaxData) { + const result = {}; + for ( const key in ajaxData ) { + if ( Object.prototype.hasOwnProperty.call(ajaxData, key) ) { + result[key] = ajaxData[key]; + } + } + return result; + } + + /** + * Injecting CleanTalk data to ajax data FormData object. + * @param {object} sourceSign + * @param {object} ajaxDataFormData + * @return {object} + */ + injectCleantalkDataToJQAjaxFormData(sourceSign, ajaxDataFormData) { + if ( + typeof sourceSign !== 'object' || + !this.isJQAjaxFormData(ajaxDataFormData) + ) { + return ajaxDataFormData; + } + + try { + // Event token + if ( + +ctPublic.bot_detector_enabled && + apbctLocalStorage.get('bot_detector_event_token') + ) { + const token = this.toolGetEventToken(); + if (token) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append('ct_bot_detector_event_token', token); + } else { + ajaxDataFormData.append('data[ct_bot_detector_event_token]', token); + } + } + } else { + // No cookie data + let noCookieData = getNoCookieData(); + if (noCookieData) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append('ct_no_cookie_hidden_field', noCookieData); + } else { + ajaxDataFormData.append('data[ct_no_cookie_hidden_field]', noCookieData); + } + } + } + + // Bot detector browser state + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append(browserState.key, browserState.value); + } else { + ajaxDataFormData.append('data[' + browserState.key + ']', browserState.value); + } + } + + // Visible fields + if (sourceSign.attachVisibleFieldsData) { + let visibleFieldsSearchResult = false; + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if (extractor) { + // Try to find form_id in FormData to find form container and + // collect visible fields only inside it + const formId = this.getFormDataField( + ajaxDataFormData, + ['form_id', 'data[form_id]'], + ); + let container = null; + if (formId && typeof formId === 'string') { + // Sanitize formId to prevent selector injection + const sanitizedFormId = formId.replace(/["\\]/g, ''); + // First, try to find by id + container = document.getElementById(sanitizedFormId); + // If not found, try to find by data-id + if (!container) { + container = document.querySelector('[data-id="' + sanitizedFormId + '"]'); + } + } + if (container) { + // Collect all input, select, textarea inside the container + const fields = container.querySelectorAll('input, select, textarea'); + // Use collectVisibleFields, passing an object with elements + const visibleFieldsObj = new ApbctAttachData().collectVisibleFields({elements: fields}); + visibleFieldsSearchResult = JSON.stringify(visibleFieldsObj); + } + } + if (typeof visibleFieldsSearchResult === 'string' && visibleFieldsSearchResult.length > 0) { + ajaxDataFormData.append('apbct_visible_fields', visibleFieldsSearchResult); + } + } + } catch (e) { + // Silently fail to not break the original request + } + + return ajaxDataFormData; + } + + /** + * Injecting CleanTalk data to ajax data string. + * @param {object} sourceSign Object of found sign to intercept. + * @param {string} ajaxDataString Original data string from ajax object. + * @return {string} + */ + injectCleantalkDataToJQAjaxString(sourceSign, ajaxDataString) { + // something wrong with incoming data + if (typeof sourceSign !== 'object' || typeof ajaxDataString !== 'string') { + return ajaxDataString; + } + let eventToken = ''; + let noCookieData = ''; + let visibleFieldsString = ''; + let browserStateString = ''; + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + const browserStateKey = sourceSign.keepUnwrapped ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; + browserStateString = browserStateKey + '=' + encodeURIComponent(browserState.value) + '&'; } - let eventToken = ''; - let noCookieData = ''; - let visibleFieldsString = ''; if ( +ctPublic.bot_detector_enabled && @@ -4127,9 +5002,9 @@ class ApbctHandler { } else { noCookieData = getNoCookieData(); if (sourceSign.keepUnwrapped) { - noCookieData = 'ct_no_cookie_hidden_field=' + noCookieData + '&'; + noCookieData = 'ct_no_cookie_hidden_field=' + encodeURIComponent(noCookieData) + '&'; } else { - noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + noCookieData + '&'; + noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + encodeURIComponent(noCookieData) + '&'; } } @@ -4152,7 +5027,7 @@ class ApbctHandler { } } - return noCookieData + eventToken + visibleFieldsString + ajaxDataString; + return noCookieData + eventToken + browserStateString + visibleFieldsString + ajaxDataString; } /** @@ -4992,67 +5867,126 @@ function ctCheckInternalIsExcludedForm(action) { }); } -let botDetectorLogLastUpdate = 0; -let botDetectorLogEventTypesCollected = []; - -// bot_detector frontend_data log alt session saving cron -if ( - ctPublicFunctions.hasOwnProperty('bot_detector_enabled') && - +ctPublicFunctions.bot_detector_enabled && - ctPublicFunctions.hasOwnProperty('data__frontend_data_log_enabled') && - ctPublicFunctions.data__frontend_data_log_enabled == 1 -) { - sendBotDetectorLogToAltSessions(1000); -} - /** - * Send BotDetector logs data to alternative sessions. - * If log_last_update has changed and log contains new event types, the log will be sent to the alternative sessions. - * @param {int} cronStartTimeout delay before cron start - * @param {int} interval check fires on interval + * Bot detector browser state. + * + * The state is passed to the site backend with the current JS->PHP transport and goes + * to the moderate request as sender_info.bot_detector_frontend_data_log. */ -function sendBotDetectorLogToAltSessions(cronStartTimeout = 3000, interval = 1000) { - setTimeout(function() { - setInterval(function() { - const currentLog = apbctLocalStorage.get('ct_bot_detector_frontend_data_log'); - if (needsSaveLogToAltSessions(currentLog)) { - botDetectorLogLastUpdate = currentLog.log_last_update; - // the log will be taken from javascriptclientdata - ctSetAlternativeCookie([], {forceAltCookies: true}); - } - }, interval); - }, cronStartTimeout); -} +class ApbctBrowserState { + static STATE_KEY = 'apbct_browser_state'; + static LOG_KEY = 'ct_bot_detector_frontend_data_log'; + static SCRIPT_SIGNS = { + botd_wrapper_loaded: 'ct-bot-detector-wrapper', + botd_logic_loaded: 'ct-bot-detector.min', + }; + /** + * This LS key is set on bot-detector side + * @type {string} + */ + static TRANSPORT_ENABLED_SIGN_KEY = 'bot_detector_log_transport_enabled'; + static botdWrapperLoaded = 0; + static botdLogicLoaded = 0; -/** - * Check if the log needs to be saved to the alt sessions. If the log has new event types, it will be saved. - * @param {object} currentLog - * @return {boolean} - */ -function needsSaveLogToAltSessions(currentLog) { - if ( - currentLog && currentLog.hasOwnProperty('log_last_update') && - botDetectorLogLastUpdate !== currentLog.log_last_update - ) { - try { - for (let i = 0; i < currentLog.records.length; i++) { - const currentType = currentLog.records[i].frontend_data.js_event; - // check if this event type was already collected - if (currentType !== undefined && botDetectorLogEventTypesCollected.includes(currentType)) { - continue; + /** + * Get the current browser state as a JSON string ready to be transferred. + * @return {string} Empty string if the bot detector is disabled or on any collecting error. + */ + static getFrontendDataLog() { + const prefix = (typeof ctPublicFunctions !== 'undefined' && ctPublicFunctions.cookiePrefix) ? + ctPublicFunctions.cookiePrefix : + ''; + const logKey = prefix + ApbctBrowserState.LOG_KEY; + const noPrefixLogKey = ApbctBrowserState.LOG_KEY; + + if (typeof apbctLocalStorage !== 'undefined' && apbctLocalStorage.get) { + const logObject = apbctLocalStorage.get(logKey) || apbctLocalStorage.get(noPrefixLogKey) || null; + if (logObject && typeof logObject === 'string') { + try { + return JSON.parse(logObject); + } catch (e) { + return ''; } - // add new event type to collection, this type will be sent to the alt sessions further - botDetectorLogEventTypesCollected.push(currentType); - return true; } + return logObject; + } + + let rawLog = localStorage.getItem(logKey); + if (!rawLog) { + rawLog = localStorage.getItem(noPrefixLogKey) || null; + } + + try { + return typeof rawLog === 'string' ? JSON.parse(rawLog) : rawLog; } catch (e) { - console.log('APBCT: bot detector log collection error: ' . e.toString()); + return ''; } } - return false; -} + /** + * + * @return {object} + */ + static asDTO() { + return { + botd_logic_loaded: ApbctBrowserState.botdLogicLoaded, + botd_wrapper_loaded: ApbctBrowserState.botdWrapperLoaded, + frontend_data_log: '', + transport_enabled: 1, + }; + } + + /** + * Look for the bot detector scripts in the page DOM. + * @return {boolean} True if both scripts are found. + */ + static detectScripts() { + if (ApbctBrowserState.botdWrapperLoaded && ApbctBrowserState.botdLogicLoaded) { + return true; + } + + const scripts = document.getElementsByTagName('script'); + + for (let i = 0; i < scripts.length; i++) { + const src = scripts[i].getAttribute('src'); + if (!src) { + continue; + } + if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_wrapper_loaded) !== -1) { + ApbctBrowserState.botdWrapperLoaded = 1; + } else if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_logic_loaded) !== -1) { + ApbctBrowserState.botdLogicLoaded = 1; + } + } + + // The bot detector logic sets this flag on its own start + return !!ApbctBrowserState.botdWrapperLoaded && !!ApbctBrowserState.botdLogicLoaded; + } +} +/** + * Get the browser state as a key/value pair to attach it to an intercepted request. + * @return {{key: string, value: string}|false} False if there is nothing to attach. + */ +function apbctGetBrowserStatePair() { // eslint-disable-line no-unused-vars + try { + ApbctBrowserState.detectScripts(); + let state = ApbctBrowserState.asDTO(); + if ( ApbctBrowserState.botdLogicLoaded ) { + const transportEnabled = localStorage.getItem(ApbctBrowserState.TRANSPORT_ENABLED_SIGN_KEY) === '1'; + if (transportEnabled) { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } else { + state.transport_enabled = 0; + } + } else { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } + return {key: ApbctBrowserState.STATE_KEY, value: JSON.stringify(state)}; + } catch (e) { + return false; + } +} let ctCheckedEmails = {}; let ctCheckedEmailsExist = {}; diff --git a/js/prebuild/apbct-public-bundle_int-protection_gathering.js b/js/prebuild/apbct-public-bundle_int-protection_gathering.js index 792acf4ad..d2b5e069d 100644 --- a/js/prebuild/apbct-public-bundle_int-protection_gathering.js +++ b/js/prebuild/apbct-public-bundle_int-protection_gathering.js @@ -2253,7 +2253,7 @@ function ctSetCookie( cookies, value, expires='') { let listOfCookieNamesToForceAlt = [ 'ct_sfw_pass_key', 'ct_sfw_passed', - 'wordpress_apbct_antibot', + 'apbct_antibot', 'apbct_anticrawler_passed', 'apbct_bot_detector_exist', 'apbct_antiflood_passed', @@ -2642,6 +2642,15 @@ function getNoCookieData() { // eslint-disable-line no-unused-vars let noCookieDataLocal = apbctLocalStorage.getCleanTalkData(); let noCookieDataSession = apbctSessionStorage.getCleanTalkData(); let noCookieData = {...noCookieDataLocal, ...noCookieDataSession}; + + // Bot detector browser state is transferred with the hidden field on the NoCookie mode + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + noCookieData[browserState.key] = browserState.value; + } + } + noCookieData = JSON.stringify(noCookieData); return '_ct_no_cookie_data_' + btoa(unescape(encodeURIComponent(noCookieData))); @@ -2669,7 +2678,21 @@ function getCleanTalkStorageDataArray() { // eslint-disable-line no-unused-vars noCookieDataFromUserActivity = {collecting_user_activity_data: collectingUserActivityData}; } - return {...noCookieDataLocal, ...noCookieDataSession, ...noCookieDataTypo, ...noCookieDataFromUserActivity}; + let browserStateData = {}; + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + browserStateData[browserState.key] = browserState.value; + } + } + + return { + ...noCookieDataLocal, + ...noCookieDataSession, + ...noCookieDataTypo, + ...noCookieDataFromUserActivity, + ...browserStateData, + }; } /** @@ -3314,6 +3337,9 @@ class ApbctHandler { const eventTokenKey = useUnwrappedCleantalkKeys ? 'ct_bot_detector_event_token' : 'data%5Bct_bot_detector_event_token%5D'; + const browserStateKey = useUnwrappedCleantalkKeys ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; if (!( +ctPublic.bot_detector_enabled && @@ -3338,6 +3364,12 @@ class ApbctHandler { } } + const browserState = apbctGetBrowserStatePair(); + if (browserState && body.indexOf('apbct_browser_state') === -1) { + addidionalCleantalkData += '&' + browserStateKey + '=' + + encodeURIComponent(browserState.value); + } + body += addidionalCleantalkData; } @@ -3354,6 +3386,11 @@ class ApbctHandler { body.append('ct_bot_detector_event_token', eventToken); } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState && !body.has(browserState.key)) { + body.append(browserState.key, browserState.value); + } } if (isNeedToAddCleantalkDataCheckJsonData) { @@ -3391,6 +3428,22 @@ class ApbctHandler { } } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + try { + const bodyObj = JSON.parse(body); + if ( + bodyObj && typeof bodyObj === 'object' && + !Object.prototype.hasOwnProperty.call(bodyObj, browserState.key) + ) { + bodyObj[browserState.key] = browserState.value; + body = JSON.stringify(bodyObj); + } + } catch (e) { + // body is not JSON — leave as is + } + } } return originalSend.apply(this, [body]); @@ -3448,6 +3501,11 @@ class ApbctHandler { } else { args[1].body.append('ct_no_cookie_hidden_field', getNoCookieData()); } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + args[1].body.append(browserState.key, browserState.value); + } } } } catch (e) { @@ -3504,6 +3562,22 @@ class ApbctHandler { * @return {string|FormData} Modified body. */ const attachFieldsToBody = function(body, fieldPair = false) { + const fieldPairs = [fieldPair, apbctGetBrowserStatePair()]; + + for (const pair of fieldPairs) { + body = attachFieldPairToBody(body, pair); + } + + return body; + }; + + /** + * Attach a single key/value pair to fetch request body + * @param {string|FormData} body Fetch request data body. + * @param {object|bool} fieldPair Key value to inject. + * @return {string|FormData} Modified body. + */ + const attachFieldPairToBody = function(body, fieldPair = false) { if (fieldPair) { if (body instanceof FormData || typeof body.append === 'function') { body.append(fieldPair.key, fieldPair.value); @@ -3761,255 +3835,1041 @@ class ApbctHandler { // Continue even if error } } - - // === WooCommerce add to cart (direct add-item URL) === - if ( - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/cart/add-item') - ) { - try { - if (+ctPublic.settings__forms__wc_add_to_cart) { - args[1].body = attachFieldsToBody( - args[1].body, - selectFieldsData(+ctPublic.bot_detector_enabled), - ); - } - } catch (e) { - // Continue even if error + + // === WooCommerce add to cart (direct add-item URL) === + if ( + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/cart/add-item') + ) { + try { + if (+ctPublic.settings__forms__wc_add_to_cart) { + args[1].body = attachFieldsToBody( + args[1].body, + selectFieldsData(+ctPublic.bot_detector_enabled), + ); + } + } catch (e) { + // Continue even if error + } + } + + // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === + if ( + +ctPublic.settings__forms__wc_add_to_cart && + ( + document.querySelectorAll( + 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', + ).length > 0 || + document.querySelectorAll('a.add_to_cart_button').length > 0 + ) && + args[0].includes('/wc/store/v1/batch') && + typeof args[1].body === 'string' + ) { + try { + const batchPayload = JSON.parse(args[1].body); + if (batchPayload.requests && Array.isArray(batchPayload.requests)) { + const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); + const browserState = apbctGetBrowserStatePair(); + for (const req of batchPayload.requests) { + const isAddItem = req.path === '/wc/store/v1/cart/add-item'; + if (isAddItem && req.body && fieldPair && fieldPair.key) { + req.body[fieldPair.key] = fieldPair.value; + } + if (isAddItem && req.body && browserState) { + req.body[browserState.key] = browserState.value; + } + } + args[1].body = JSON.stringify(batchPayload); + } + } catch (e) { + // Continue even if error + } + } + + // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === + preventOriginalFetch = await processIframeCommonFetch(url, args); + + // Return original fetch result if not prevented + if (!preventOriginalFetch) { + return originalFetch.apply(this, args); + } + } catch (error) { + // In case of any error in our interceptor, call original fetch + return originalFetch.apply(this, args); + } + }; + } + + /** + * Prepare jQuery.ajaxPrefilter to add CleanTalk data to jQuery ajax requests. + * Notes: + * - ajaxSetup.beforeSend is not used: a request can supply its own beforeSend and drop the default. + * - ajaxPrefilter runs for every jQuery ajax call after options are merged, so injection is guaranteed. + * - Form signs are checked on the request data/url at send time. + * - Any sign of the form HTML of the caller is insignificant in this process. + * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script + * will work independing if jQuery is loaded by CleanTalk or not + * @return {void} + */ + catchJqueryAjax() { + if ( typeof jQuery !== 'undefined' && typeof jQuery.ajaxPrefilter === 'function' ) { + jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { + const handler = new ApbctHandler(); + const sourceSign = handler.searchSignsForJQAjaxInjection(options, originalOptions); + if (sourceSign.found !== false) { + options.data = handler.injectCleantalkDataToJQAjax( + sourceSign, + handler.getJQAjaxPayloadForInject(options, originalOptions), + options, + ); + } + }); + } + } + + /** + * jQuery.param() on URLSearchParams/FormData can collapse options.data to "". + * Sign search already falls back to originalOptions; inject must use that payload too. + * @param {object} options + * @param {object=} originalOptions + * @return {*} + */ + getJQAjaxPayloadForInject(options, originalOptions) { + const current = options && options.data; + const original = originalOptions && originalOptions.data; + if ( this.jqAjaxPayloadWasCollapsed(current, original) ) { + return original; + } + return current; + } + + /** + * @param {*} current + * @param {*} original + * @return {boolean} + */ + jqAjaxPayloadWasCollapsed(current, original) { + if ( original === null || typeof original === 'undefined' ) { + return false; + } + if ( current === original ) { + return false; + } + const currentEmpty = current === '' || current === null || typeof current === 'undefined'; + if ( !currentEmpty ) { + return false; + } + if ( typeof original === 'string' ) { + return original !== ''; + } + return this.isJQAjaxFormData(original) || + this.isJQAjaxURLSearchParams(original) || + this.isJQAjaxPlainObjectOrArray(original); + } + + /** + * Normalize jQuery ajax data to a query string for sign search. + * Objects and serializeArray are read structurally so search never calls jQuery.param. + * Also reads known sign fields from the URL (IE11 FormData cannot be enumerated). + * @param {object} ajaxObject Ajax options object. + * @return {string} + */ + getJQAjaxDataAsString(ajaxObject) { + if ( !ajaxObject || typeof ajaxObject !== 'object' ) { + return ''; + } + let fromData = ''; + if ( typeof ajaxObject.data === 'string' ) { + fromData = ajaxObject.data; + } else if ( this.isJQAjaxPlainObjectOrArray(ajaxObject.data) ) { + fromData = this.getStructuredJQAjaxSignString(ajaxObject.data); + } else if ( this.isJQAjaxURLSearchParams(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } else if ( this.isJQAjaxFormData(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } + // Native IE11 FormData is write-only (no get/forEach/entries). Signs then come from the URL. + const fromUrl = this.collectKnownSignStringFromUrl(ajaxObject.url); + if ( fromData && fromUrl ) { + return fromData + '&' + fromUrl; + } + return fromData || fromUrl; + } + + /** + * Build a sign string from top-level fields without serializing the whole payload. + * @param {object|Array} data + * @return {string} + */ + getStructuredJQAjaxSignString(data) { + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return this.getSerializeArraySignString(data); + } + const parts = []; + const action = this.getPlainObjectSignField(data, 'action'); + if ( typeof action === 'string' && action !== '' ) { + parts.push('action=' + action); + } + const nonce = this.getPlainObjectSignField(data, 'ur_frontend_form_nonce'); + if ( nonce !== null ) { + parts.push('ur_frontend_form_nonce=' + nonce); + } + if ( this.plainObjectHasTwtCcSignup(data) ) { + parts.push('twt_cc_signup=1'); + } + return parts.join('&'); + } + + /** + * Read action/nonce from top-level, data[key], or nested data.key. + * @param {object} data + * @param {string} key + * @return {string|number|null} + */ + getPlainObjectSignField(data, key) { + if ( !data || typeof data !== 'object' ) { + return null; + } + if ( this.isJQAjaxScalarSignValue(data[key]) ) { + return data[key]; + } + const bracketKey = 'data[' + key + ']'; + if ( this.isJQAjaxScalarSignValue(data[bracketKey]) ) { + return data[bracketKey]; + } + if ( + data.data && + typeof data.data === 'object' && + Object.prototype.toString.call(data.data) !== '[object Array]' && + this.isJQAjaxScalarSignValue(data.data[key]) + ) { + return data.data[key]; + } + return null; + } + + /** + * @param {*} value + * @return {boolean} + */ + isJQAjaxScalarSignValue(value) { + return typeof value === 'string' || typeof value === 'number'; + } + + /** + * @param {object} data + * @param {number=} depth + * @return {boolean} + */ + plainObjectHasTwtCcSignup(data, depth) { + if ( !data || typeof data !== 'object' ) { + return false; + } + if ( typeof depth === 'undefined' ) { + depth = 0; + } + if ( depth > 2 ) { + return false; + } + for ( const key in data ) { + if ( !Object.prototype.hasOwnProperty.call(data, key) ) { + continue; + } + const normalizedKey = this.unwrapJQAjaxFormDataKey(key); + if ( normalizedKey === 'twt_cc_signup' || key.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + const value = data[key]; + if ( typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + if ( + value && + typeof value === 'object' && + Object.prototype.toString.call(value) !== '[object Array]' + ) { + if ( this.plainObjectHasTwtCcSignup(value, depth + 1) ) { + return true; + } + } + } + return false; + } + + /** + * @param {Array} entries + * @return {string} + */ + getSerializeArraySignString(entries) { + const parts = []; + for ( let i = 0; i < entries.length; i++ ) { + const entry = entries[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + continue; + } + const value = entry.value; + const normalizedKey = this.unwrapJQAjaxFormDataKey(entry.name); + if ( this.isJQAjaxKnownSignField(normalizedKey, value) ) { + parts.push(normalizedKey + '=' + value); + } + } + return parts.join('&'); + } + + /** + * True for serializeArray payloads, including an empty array. + * @param {Array} data + * @return {boolean} + */ + isJQAjaxSerializeArray(data) { + if ( Object.prototype.toString.call(data) !== '[object Array]' ) { + return false; + } + for ( let i = 0; i < data.length; i++ ) { + const entry = data[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + return false; + } + } + return true; + } + + /** + * Cross-realm URLSearchParams (instanceof fails across windows). + * @param {*} data + * @return {boolean} + */ + isJQAjaxURLSearchParams(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object URLSearchParams]' ) { + return true; + } + if ( tag === '[object FormData]' ) { + return false; + } + return typeof data.sort === 'function' && typeof data.get === 'function'; + } + + /** + * Cross-realm FormData, including common polyfills. + * @param {*} data + * @return {boolean} + */ + isJQAjaxFormData(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) || this.isJQAjaxURLSearchParams(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object FormData]' ) { + return true; + } + if ( tag === '[object Headers]' || typeof data.getSetCookie === 'function' ) { + return false; + } + return typeof data.forEach === 'function' || + typeof data.get === 'function' || + typeof data.entries === 'function'; + } + + /** + * Collect only known sign fields from FormData / URLSearchParams. + * Unwrap data[action] so later action=... checks match. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + collectKnownSignStringFromKeyValueBag(bag) { + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' ) { + return; + } + const valueAsString = String(value); + const normalizedKey = unwrapKey(key); + if ( + knownKeys[normalizedKey] || + valueAsString.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + valueAsString); + } + }); + if ( collected ) { + return parts.join('&'); + } + if ( typeof bag.get !== 'function' ) { + return ''; + } + const keysToProbe = [ + 'action', + 'ur_frontend_form_nonce', + 'twt_cc_signup', + ]; + const getParts = []; + for ( let i = 0; i < keysToProbe.length; i++ ) { + const key = keysToProbe[i]; + const value = this.getFormDataScalarValue(bag, [key, 'data[' + key + ']']); + if ( value !== null ) { + getParts.push(key + '=' + value); + } + } + return getParts.join('&'); + } + + /** + * Known sign fields from a request URL query. IE11-safe (no URLSearchParams). + * @param {string} url + * @return {string} + */ + collectKnownSignStringFromUrl(url) { + if ( typeof url !== 'string' || url === '' ) { + return ''; + } + const queryIndex = url.indexOf('?'); + if ( queryIndex === -1 || queryIndex === url.length - 1 ) { + return ''; + } + const hashIndex = url.indexOf('#', queryIndex); + const query = hashIndex === -1 ? + url.slice(queryIndex + 1) : + url.slice(queryIndex + 1, hashIndex); + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const pairs = query.split('&'); + for ( let i = 0; i < pairs.length; i++ ) { + const pair = pairs[i]; + if ( !pair ) { + continue; + } + const eq = pair.indexOf('='); + let rawKey = eq === -1 ? pair : pair.slice(0, eq); + let rawValue = eq === -1 ? '' : pair.slice(eq + 1); + try { + rawKey = decodeURIComponent(rawKey.replace(/\+/g, ' ')); + rawValue = decodeURIComponent(rawValue.replace(/\+/g, ' ')); + } catch (e) { + continue; + } + const normalizedKey = unwrapKey(rawKey); + if ( + knownKeys[normalizedKey] || + rawValue.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + rawValue); + } + } + return parts.join('&'); + } + + /** + * Walk FormData/URLSearchParams via forEach, then entries() for polyfills that only have an iterator. + * @param {FormData|URLSearchParams} bag + * @param {Function} callback + * @return {boolean} + */ + forEachJQAjaxKeyValueBag(bag, callback) { + if ( typeof bag.forEach === 'function' ) { + try { + bag.forEach(callback); + return true; + } catch (e) { + // Fall through to entries(). + } + } + if ( typeof bag.entries !== 'function' ) { + return false; + } + try { + const iterator = bag.entries(); + if ( !iterator || typeof iterator.next !== 'function' ) { + return false; + } + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + callback(pair[1], pair[0]); + } + step = iterator.next(); + } + return true; + } catch (e) { + return false; + } + } + + /** + * @return {Object} + */ + getJQAjaxKnownSignKeys() { + const knownKeys = Object.create(null); + knownKeys.action = true; + knownKeys.ur_frontend_form_nonce = true; + knownKeys.twt_cc_signup = true; + return knownKeys; + } + + /** + * @param {string} normalizedKey + * @param {*} value + * @return {boolean} + */ + isJQAjaxKnownSignField(normalizedKey, value) { + if ( + normalizedKey === 'action' || + normalizedKey === 'ur_frontend_form_nonce' || + normalizedKey === 'twt_cc_signup' || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + return true; + } + return typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1; + } + + /** + * Treat data[action] as action for WP-style payloads. + * @param {string} key + * @return {string} + */ + unwrapJQAjaxFormDataKey(key) { + if ( typeof key !== 'string' ) { + return ''; + } + if ( key.length > 6 && key.indexOf('data[') === 0 && key.charAt(key.length - 1) === ']' ) { + return key.slice(5, -1); + } + return key; + } + + /** + * @param {FormData} formData + * @param {Array.} keys + * @return {string|number|null} + */ + getFormDataScalarValue(formData, keys) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && (typeof value === 'string' || typeof value === 'number') ) { + return value; + } + } + return null; + } + + /** + * True for arrays and plain objects that jQuery.param can serialize safely. + * @param {*} data + * @return {boolean} + */ + isJQAjaxPlainObjectOrArray(data) { + if ( data === null || typeof data !== 'object' ) { + return false; + } + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return true; + } + if ( typeof jQuery !== 'undefined' && typeof jQuery.isPlainObject === 'function' ) { + return jQuery.isPlainObject(data); + } + const proto = Object.getPrototypeOf(data); + return proto === Object.prototype || proto === null; + } + + /** + * Search for sign within AJAX data to do inject CleanTalk data. + * @param {object} ajaxObject Ajax object. + * @param {object=} originalOptions Original jQuery ajax options before merge. + * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + */ + searchSignsForJQAjaxInjection(ajaxObject, originalOptions) { + let sourceSign = { + 'found': false, + 'keepUnwrapped': false, + 'attachVisibleFieldsData': false, + }; + let dataString = this.getJQAjaxDataAsString(ajaxObject); + if ( !dataString && originalOptions && originalOptions !== ajaxObject ) { + dataString = this.getJQAjaxDataAsString(originalOptions); + } + + if ( dataString.indexOf('action=fl_builder_subscribe_form_submit') !== -1 ) { + sourceSign.found = 'fl_builder_subscribe_form_submit'; + } + if ( dataString.indexOf('twt_cc_signup') !== -1 ) { + sourceSign.found = 'twt_cc_signup'; + } + if ( dataString.indexOf('action=mailpoet') !== -1 ) { + sourceSign.found = 'action=mailpoet'; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=user_registration') !== -1 && + dataString.indexOf('ur_frontend_form_nonce') !== -1 + ) { + sourceSign.found = 'action=user_registration'; + } + if ( dataString.indexOf('action=happyforms_message') !== -1 ) { + sourceSign.found = 'action=happyforms_message'; + } + if ( dataString.indexOf('action=new_activity_comment') !== -1 ) { + sourceSign.found = 'action=new_activity_comment'; + } + if ( dataString.indexOf('action=wwlc_create_user') !== -1 ) { + sourceSign.found = 'action=wwlc_create_user'; + } + if ( dataString.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 ) { + sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=drplus_signup') !== -1 ) { + sourceSign.found = 'action=drplus_signup'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=bt_cc') !== -1 ) { + sourceSign.found = 'action=bt_cc'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=wpr_form_builder_email') !== -1 ) { + sourceSign.found = 'action=wpr_form_builder_email'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=nf_ajax_submit') !== -1 ) { + sourceSign.found = 'action=nf_ajax_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=uael_register_user') !== -1 && + ctPublic.data__cookies_type === 'none' + ) { + sourceSign.found = 'action=uael_register_user'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=SQBSubmitQuizAjax') !== -1 ) { + sourceSign.found = 'action=SQBSubmitQuizAjax'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=user_registration_user_form_submit') !== -1 ) { + sourceSign.found = 'action=user_registration_user_form_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=bloom_subscribe') !== -1 ) { + sourceSign.found = 'action=bloom_subscribe'; + sourceSign.keepUnwrapped = true; + } + if ( + this.isJQAjaxFormData(ajaxObject.data) && + typeof ajaxObject.data.get === 'function' && + ajaxObject.data.get('action') === 'pafe_ajax_form_builder' + ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } else if ( dataString.indexOf('action=pafe_ajax_form_builder') !== -1 ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } + + // woocommerce add to cart is based on URL + if ( typeof ajaxObject.url === 'string' && ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1 ) { + sourceSign.found = 'wc-ajax=add_to_cart'; + // GET/HEAD: PHP reads Get::get('ct_bot_detector_event_token'), not data[...]. + if ( this.isJQAjaxNoContentMethod(ajaxObject) ) { + sourceSign.keepUnwrapped = true; + } + } + + return sourceSign; + } + + /** + * Inject CleanTalk data into jQuery ajax payload of any supported type. + * @param {object} sourceSign + * @param {*} ajaxData + * @param {object=} ajaxOptions jQuery ajax options (traditional, processData, contentType). + * Keep URLSearchParams/objects when processData or contentType is false. + * URLSearchParams must also disable processData, or jQuery.param() later yields "". + * GET/HEAD never keep the original type: jQuery only puts string data on the URL. + * @return {*} + */ + injectCleantalkDataToJQAjax(sourceSign, ajaxData, ajaxOptions) { + const traditional = ajaxOptions && ajaxOptions.traditional; + const keepOriginalType = !this.isJQAjaxNoContentMethod(ajaxOptions) && !!(ajaxOptions && ( + ajaxOptions.processData === false || + ajaxOptions.contentType === false + )); + + if ( ajaxData === null || typeof ajaxData === 'undefined' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ''); + } + if ( typeof ajaxData === 'string' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData); + } + if ( this.isJQAjaxPlainObjectOrArray(ajaxData) ) { + if ( keepOriginalType ) { + if ( Object.prototype.toString.call(ajaxData) === '[object Array]' ) { + if ( this.isJQAjaxSerializeArray(ajaxData) ) { + return this.injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData); + } + return ajaxData; + } + return this.injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData); + } + try { + if ( typeof jQuery !== 'undefined' && typeof jQuery.param === 'function' ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + jQuery.param(ajaxData, traditional), + ); + } + } catch (e) { + return ajaxData; + } + return ajaxData; + } + if ( this.isJQAjaxURLSearchParams(ajaxData) ) { + if ( keepOriginalType ) { + this.preserveJQAjaxURLSearchParamsOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxKeyValue( + sourceSign, + this.cloneURLSearchParams(ajaxData), + ); + } + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData.toString()); + } + if ( this.isJQAjaxFormData(ajaxData) ) { + if ( this.isJQAjaxNoContentMethod(ajaxOptions) ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + this.serializeJQAjaxKeyValueBag(ajaxData), + ); + } + this.preserveJQAjaxFormDataOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxFormData( + sourceSign, + this.cloneFormData(ajaxData), + ); + } + return ajaxData; + } + + /** + * GET/HEAD have no body. Missing type is GET (jQuery default). + * @param {object=} ajaxOptions + * @return {boolean} + */ + isJQAjaxNoContentMethod(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return false; + } + const type = ajaxOptions.type || ajaxOptions.method; + if ( typeof type !== 'string' || type === '' ) { + return true; + } + const method = type.toUpperCase(); + return method === 'GET' || method === 'HEAD'; + } + + /** + * Collect CleanTalk fields to append to a key/value payload. + * @param {object} sourceSign + * @return {Array.>} + */ + getCleantalkJQAjaxFieldPairs(sourceSign) { + const pairs = []; + const wrapKey = function(key) { + return sourceSign.keepUnwrapped ? key : 'data[' + key + ']'; + }; + + if ( + +ctPublic.bot_detector_enabled && + apbctLocalStorage.get('bot_detector_event_token') + ) { + const token = this.toolGetEventToken(); + if ( token ) { + pairs.push([wrapKey('ct_bot_detector_event_token'), token]); + } + } else { + const noCookieData = getNoCookieData(); + if ( noCookieData ) { + pairs.push([wrapKey('ct_no_cookie_hidden_field'), noCookieData]); + } + } + + const browserState = apbctGetBrowserStatePair(); + if ( browserState ) { + const browserStateKey = sourceSign.keepUnwrapped ? + browserState.key : + 'data[' + browserState.key + ']'; + pairs.push([browserStateKey, browserState.value]); + } + + return pairs; + } + + /** + * jQuery.param(FormData) after the prefilter yields "". Keep the body as FormData. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxFormDataOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + ajaxOptions.contentType = false; + } + + /** + * jQuery.param(URLSearchParams) after the prefilter yields "". Keep the body as URLSearchParams. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxURLSearchParamsOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + } + + /** + * Read a FormData field via get(), forEach(), or entries(). + * Native IE11 FormData is write-only and cannot be read. + * @param {FormData} formData + * @param {Array.} keys + * @return {*} + */ + getFormDataField(formData, keys) { + if ( typeof formData.get === 'function' ) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && typeof value !== 'undefined' ) { + return value; + } + } + } + if ( typeof formData.forEach === 'function' ) { + let found = null; + formData.forEach(function(value, key) { + if ( found !== null ) { + return; + } + for ( let i = 0; i < keys.length; i++ ) { + if ( key === keys[i] ) { + found = value; + return; } } - - // === WooCommerce add to cart (batch API - /wc/store/v1/batch) === - if ( - +ctPublic.settings__forms__wc_add_to_cart && - ( - document.querySelectorAll( - 'button.add_to_cart_button, button.ajax_add_to_cart, button.single_add_to_cart_button', - ).length > 0 || - document.querySelectorAll('a.add_to_cart_button').length > 0 - ) && - args[0].includes('/wc/store/v1/batch') && - typeof args[1].body === 'string' - ) { - try { - const batchPayload = JSON.parse(args[1].body); - if (batchPayload.requests && Array.isArray(batchPayload.requests)) { - const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); - for (const req of batchPayload.requests) { - const isAddItem = req.path === '/wc/store/v1/cart/add-item'; - if (isAddItem && req.body && fieldPair && fieldPair.key) { - req.body[fieldPair.key] = fieldPair.value; + }); + if ( found !== null ) { + return found; + } + } + if ( typeof formData.entries === 'function' ) { + try { + const iterator = formData.entries(); + if ( iterator && typeof iterator.next === 'function' ) { + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + for ( let i = 0; i < keys.length; i++ ) { + if ( pair[0] === keys[i] ) { + return pair[1]; } } - args[1].body = JSON.stringify(batchPayload); } - } catch (e) { - // Continue even if error + step = iterator.next(); } } - - // === Bitrix24 / sender.com external forms (config-driven, see externalFormHandlers) === - preventOriginalFetch = await processIframeCommonFetch(url, args); - - // Return original fetch result if not prevented - if (!preventOriginalFetch) { - return originalFetch.apply(this, args); - } - } catch (error) { - // In case of any error in our interceptor, call original fetch - return originalFetch.apply(this, args); + } catch (e) { + return null; } - }; + } + return null; } /** - * Prepare jQuery.ajaxSetup to add nocookie data to the jQuery ajax request. - * Notes: - * - Do it just once, the ajaxSetup.beforeSend will be overwritten for any calls. - * - Signs of forms need to be caught will be checked during ajaxSetup.settings.data process on send. - * - Any sign of the form HTML of the caller is insignificant in this process. - * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script - * will work independing if jQuery is loaded by CleanTalk or not - * @return {void} + * Clone URLSearchParams so the caller's instance is not mutated. + * @param {URLSearchParams} params + * @return {URLSearchParams} */ - catchJqueryAjax() { - if ( typeof jQuery !== 'undefined') { - // this code run on base ajax rules - so do not work due scripts use it's own ajax object injections - if ( typeof jQuery.ajaxSetup === 'function' ) { - jQuery.ajaxSetup({ - beforeSend: function(xhr, settings) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(settings, 'ajaxSetup'); - if (sourceSign.found !== false) { - settings.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, settings.data); - } - }, - }); + cloneURLSearchParams(params) { + const serialized = typeof params.toString === 'function' ? params.toString() : ''; + if ( typeof params.constructor === 'function' && params.constructor !== Object ) { + try { + return new params.constructor(serialized); + } catch (e) { + // Fall through to the current-window constructor. } - // this code run on ANY ajax on ANY script queue status - // todo Probably move all ajaxSetup actions to ajaxPrefilter - if ( typeof jQuery.ajaxPrefilter === 'function' ) { - jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(options, 'ajaxPrefilter'); - if (sourceSign.found !== false) { - if (typeof options.data === 'string') { - options.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, options.data); - } - if ( - typeof options.data === 'object' && - typeof options.data.append === 'function' - ) { - options.data = handler.injectCleantalkDataToJQAjaxFormData(sourceSign, options.data); - } - } - }); + } + if ( typeof URLSearchParams === 'function' ) { + try { + return new URLSearchParams(serialized); + } catch (e) { + return params; } } + return params; } /** - * Search for sign within AJAX data to do inject CleanTalk data. - * @param {object} ajaxObject Ajax object. - * @param {string} catchOn Function should be catched on. - * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} + * Clone FormData when it can be enumerated (forEach or entries); otherwise reuse. + * @param {FormData} formData + * @return {FormData} */ - searchSignsForJQAjaxInjection(ajaxObject, catchOn = 'ajaxSetup') { - let sourceSign = { - 'found': false, - 'keepUnwrapped': false, - 'attachVisibleFieldsData': false, - }; - // on ajaxSetup - if (catchOn === 'ajaxSetup') { - // settings data is string (important!) - if ( typeof ajaxObject.data === 'string' ) { - if ( - ajaxObject.data.indexOf('action=fl_builder_subscribe_form_submit') !== -1 - ) { - sourceSign.found = 'fl_builder_subscribe_form_submit'; - } - if ( - ajaxObject.data.indexOf('twt_cc_signup') !== -1 - ) { - sourceSign.found = 'twt_cc_signup'; - } - if ( - ajaxObject.data.indexOf('action=mailpoet') !== -1 - ) { - sourceSign.found = 'action=mailpoet'; - sourceSign.attachVisibleFieldsData = true; - } - - if ( - ajaxObject.data.indexOf('action=user_registration') !== -1 && - ajaxObject.data.indexOf('ur_frontend_form_nonce') !== -1 - ) { - sourceSign.found = 'action=user_registration'; - } - - if (ajaxObject.data.indexOf('action=happyforms_message') !== -1) { - sourceSign.found = 'action=happyforms_message'; - } + cloneFormData(formData) { + try { + const clone = new FormData(); + const copied = this.forEachJQAjaxKeyValueBag(formData, function(value, key) { + clone.append(key, value); + }); + if ( copied ) { + return clone; + } + } catch (e) { + return formData; + } + return formData; + } - if ( - ajaxObject.data.indexOf('action=new_activity_comment') !== -1 - ) { - sourceSign.found = 'action=new_activity_comment'; - } - if ( - ajaxObject.data.indexOf('action=wwlc_create_user') !== -1 - ) { - sourceSign.found = 'action=wwlc_create_user'; - } - if ( - ajaxObject.data.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 - ) { - sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=drplus_signup') !== -1 - ) { - sourceSign.found = 'action=drplus_signup'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=bt_cc') !== -1 - ) { - sourceSign.found = 'action=bt_cc'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=wpr_form_builder_email') !== -1 - ) { - sourceSign.found = 'action=wpr_form_builder_email'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=nf_ajax_submit') !== -1 - ) { - sourceSign.found = 'action=nf_ajax_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=uael_register_user') !== -1 && - ctPublic.data__cookies_type === 'none' - ) { - sourceSign.found = 'action=uael_register_user'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=SQBSubmitQuizAjax') !== -1 - ) { - sourceSign.found = 'action=SQBSubmitQuizAjax'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=user_registration_user_form_submit') !== -1 - ) { - sourceSign.found = 'action=user_registration_user_form_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } + /** + * Form-urlencoded string from FormData/URLSearchParams. Skip File/Blob values. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + serializeJQAjaxKeyValueBag(bag) { + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { + return; } - // wooocommerce add to cart is based on URL - if ( typeof ajaxObject.url === 'string' ) { - if (ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1) { - sourceSign.found = 'wc-ajax=add_to_cart'; + parts.push(encodeURIComponent(String(key)) + '=' + encodeURIComponent(String(value))); + }); + if ( collected ) { + return parts.join('&'); + } + return ''; + } + + /** + * Inject CleanTalk fields into URLSearchParams without changing the payload type. + * @param {object} sourceSign + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + injectCleantalkDataToJQAjaxKeyValue(sourceSign, params) { + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + params.append(pairs[i][0], pairs[i][1]); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( extractor ) { + const extracted = extractor.extract(params.toString()); + if ( typeof extracted === 'string' ) { + params.append('apbct_visible_fields', extracted); } } } + return params; + } - // on ajaxPrefilter - if (catchOn === 'ajaxPrefilter') { - if (typeof ajaxObject.data === 'string') { - if (ajaxObject.data.indexOf('action=bloom_subscribe') !== -1) { - sourceSign.found = 'action=bloom_subscribe'; - sourceSign.keepUnwrapped = true; + /** + * Inject CleanTalk fields into a jQuery serializeArray payload. + * @param {object} sourceSign + * @param {Array} ajaxData + * @return {Array} + */ + injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData) { + const result = ajaxData.slice(); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result.push({ + name: pairs[i][0], + value: pairs[i][1], + }); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' + ) { + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.push({ + name: 'apbct_visible_fields', + value: extracted, + }); } } + } + return result; + } + /** + * Inject CleanTalk fields into a plain object without changing the payload type. + * @param {object} sourceSign + * @param {object} ajaxData + * @return {object} + */ + injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData) { + const result = typeof jQuery !== 'undefined' && typeof jQuery.extend === 'function' ? + jQuery.extend({}, ajaxData) : + this.clonePlainObject(ajaxData); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result[pairs[i][0]] = pairs[i][1]; + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); if ( - typeof ajaxObject.data === 'object' && - ajaxObject.data !== null && - typeof ajaxObject.data.get === 'function' + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' ) { - if (ajaxObject.data.get('action') === 'pafe_ajax_form_builder') { - sourceSign.found = 'action=pafe_ajax_form_builder'; - sourceSign.keepUnwrapped = true; + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.apbct_visible_fields = extracted; } } } + return result; + } - return sourceSign; + /** + * IE11-safe shallow copy of a plain object. + * @param {object} ajaxData + * @return {object} + */ + clonePlainObject(ajaxData) { + const result = {}; + for ( const key in ajaxData ) { + if ( Object.prototype.hasOwnProperty.call(ajaxData, key) ) { + result[key] = ajaxData[key]; + } + } + return result; } /** @@ -4021,8 +4881,7 @@ class ApbctHandler { injectCleantalkDataToJQAjaxFormData(sourceSign, ajaxDataFormData) { if ( typeof sourceSign !== 'object' || - typeof ajaxDataFormData !== 'object' || - !(ajaxDataFormData instanceof FormData) + !this.isJQAjaxFormData(ajaxDataFormData) ) { return ajaxDataFormData; } @@ -4053,6 +4912,16 @@ class ApbctHandler { } } + // Bot detector browser state + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append(browserState.key, browserState.value); + } else { + ajaxDataFormData.append('data[' + browserState.key + ']', browserState.value); + } + } + // Visible fields if (sourceSign.attachVisibleFieldsData) { let visibleFieldsSearchResult = false; @@ -4060,13 +4929,10 @@ class ApbctHandler { if (extractor) { // Try to find form_id in FormData to find form container and // collect visible fields only inside it - let formId = null; - for (let pair of ajaxDataFormData.entries()) { - if (pair[0] === 'form_id' || pair[0] === 'data[form_id]') { - formId = pair[1]; - break; - } - } + const formId = this.getFormDataField( + ajaxDataFormData, + ['form_id', 'data[form_id]'], + ); let container = null; if (formId && typeof formId === 'string') { // Sanitize formId to prevent selector injection @@ -4111,6 +4977,15 @@ class ApbctHandler { let eventToken = ''; let noCookieData = ''; let visibleFieldsString = ''; + let browserStateString = ''; + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + const browserStateKey = sourceSign.keepUnwrapped ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; + browserStateString = browserStateKey + '=' + encodeURIComponent(browserState.value) + '&'; + } if ( +ctPublic.bot_detector_enabled && @@ -4127,9 +5002,9 @@ class ApbctHandler { } else { noCookieData = getNoCookieData(); if (sourceSign.keepUnwrapped) { - noCookieData = 'ct_no_cookie_hidden_field=' + noCookieData + '&'; + noCookieData = 'ct_no_cookie_hidden_field=' + encodeURIComponent(noCookieData) + '&'; } else { - noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + noCookieData + '&'; + noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + encodeURIComponent(noCookieData) + '&'; } } @@ -4152,7 +5027,7 @@ class ApbctHandler { } } - return noCookieData + eventToken + visibleFieldsString + ajaxDataString; + return noCookieData + eventToken + browserStateString + visibleFieldsString + ajaxDataString; } /** @@ -5836,67 +6711,126 @@ function apbctCancelAutocomplete(element) { })); } -let botDetectorLogLastUpdate = 0; -let botDetectorLogEventTypesCollected = []; - -// bot_detector frontend_data log alt session saving cron -if ( - ctPublicFunctions.hasOwnProperty('bot_detector_enabled') && - +ctPublicFunctions.bot_detector_enabled && - ctPublicFunctions.hasOwnProperty('data__frontend_data_log_enabled') && - ctPublicFunctions.data__frontend_data_log_enabled == 1 -) { - sendBotDetectorLogToAltSessions(1000); -} - /** - * Send BotDetector logs data to alternative sessions. - * If log_last_update has changed and log contains new event types, the log will be sent to the alternative sessions. - * @param {int} cronStartTimeout delay before cron start - * @param {int} interval check fires on interval + * Bot detector browser state. + * + * The state is passed to the site backend with the current JS->PHP transport and goes + * to the moderate request as sender_info.bot_detector_frontend_data_log. */ -function sendBotDetectorLogToAltSessions(cronStartTimeout = 3000, interval = 1000) { - setTimeout(function() { - setInterval(function() { - const currentLog = apbctLocalStorage.get('ct_bot_detector_frontend_data_log'); - if (needsSaveLogToAltSessions(currentLog)) { - botDetectorLogLastUpdate = currentLog.log_last_update; - // the log will be taken from javascriptclientdata - ctSetAlternativeCookie([], {forceAltCookies: true}); - } - }, interval); - }, cronStartTimeout); -} +class ApbctBrowserState { + static STATE_KEY = 'apbct_browser_state'; + static LOG_KEY = 'ct_bot_detector_frontend_data_log'; + static SCRIPT_SIGNS = { + botd_wrapper_loaded: 'ct-bot-detector-wrapper', + botd_logic_loaded: 'ct-bot-detector.min', + }; + /** + * This LS key is set on bot-detector side + * @type {string} + */ + static TRANSPORT_ENABLED_SIGN_KEY = 'bot_detector_log_transport_enabled'; + static botdWrapperLoaded = 0; + static botdLogicLoaded = 0; -/** - * Check if the log needs to be saved to the alt sessions. If the log has new event types, it will be saved. - * @param {object} currentLog - * @return {boolean} - */ -function needsSaveLogToAltSessions(currentLog) { - if ( - currentLog && currentLog.hasOwnProperty('log_last_update') && - botDetectorLogLastUpdate !== currentLog.log_last_update - ) { - try { - for (let i = 0; i < currentLog.records.length; i++) { - const currentType = currentLog.records[i].frontend_data.js_event; - // check if this event type was already collected - if (currentType !== undefined && botDetectorLogEventTypesCollected.includes(currentType)) { - continue; + /** + * Get the current browser state as a JSON string ready to be transferred. + * @return {string} Empty string if the bot detector is disabled or on any collecting error. + */ + static getFrontendDataLog() { + const prefix = (typeof ctPublicFunctions !== 'undefined' && ctPublicFunctions.cookiePrefix) ? + ctPublicFunctions.cookiePrefix : + ''; + const logKey = prefix + ApbctBrowserState.LOG_KEY; + const noPrefixLogKey = ApbctBrowserState.LOG_KEY; + + if (typeof apbctLocalStorage !== 'undefined' && apbctLocalStorage.get) { + const logObject = apbctLocalStorage.get(logKey) || apbctLocalStorage.get(noPrefixLogKey) || null; + if (logObject && typeof logObject === 'string') { + try { + return JSON.parse(logObject); + } catch (e) { + return ''; } - // add new event type to collection, this type will be sent to the alt sessions further - botDetectorLogEventTypesCollected.push(currentType); - return true; } + return logObject; + } + + let rawLog = localStorage.getItem(logKey); + if (!rawLog) { + rawLog = localStorage.getItem(noPrefixLogKey) || null; + } + + try { + return typeof rawLog === 'string' ? JSON.parse(rawLog) : rawLog; } catch (e) { - console.log('APBCT: bot detector log collection error: ' . e.toString()); + return ''; } } - return false; -} + /** + * + * @return {object} + */ + static asDTO() { + return { + botd_logic_loaded: ApbctBrowserState.botdLogicLoaded, + botd_wrapper_loaded: ApbctBrowserState.botdWrapperLoaded, + frontend_data_log: '', + transport_enabled: 1, + }; + } + + /** + * Look for the bot detector scripts in the page DOM. + * @return {boolean} True if both scripts are found. + */ + static detectScripts() { + if (ApbctBrowserState.botdWrapperLoaded && ApbctBrowserState.botdLogicLoaded) { + return true; + } + + const scripts = document.getElementsByTagName('script'); + + for (let i = 0; i < scripts.length; i++) { + const src = scripts[i].getAttribute('src'); + if (!src) { + continue; + } + if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_wrapper_loaded) !== -1) { + ApbctBrowserState.botdWrapperLoaded = 1; + } else if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_logic_loaded) !== -1) { + ApbctBrowserState.botdLogicLoaded = 1; + } + } + + // The bot detector logic sets this flag on its own start + return !!ApbctBrowserState.botdWrapperLoaded && !!ApbctBrowserState.botdLogicLoaded; + } +} +/** + * Get the browser state as a key/value pair to attach it to an intercepted request. + * @return {{key: string, value: string}|false} False if there is nothing to attach. + */ +function apbctGetBrowserStatePair() { // eslint-disable-line no-unused-vars + try { + ApbctBrowserState.detectScripts(); + let state = ApbctBrowserState.asDTO(); + if ( ApbctBrowserState.botdLogicLoaded ) { + const transportEnabled = localStorage.getItem(ApbctBrowserState.TRANSPORT_ENABLED_SIGN_KEY) === '1'; + if (transportEnabled) { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } else { + state.transport_enabled = 0; + } + } else { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } + return {key: ApbctBrowserState.STATE_KEY, value: JSON.stringify(state)}; + } catch (e) { + return false; + } +} let ctCheckedEmails = {}; let ctCheckedEmailsExist = {}; diff --git a/js/src/cleantalk-admin-settings-page.js b/js/src/cleantalk-admin-settings-page.js index 05cf500b6..3d576e00f 100644 --- a/js/src/cleantalk-admin-settings-page.js +++ b/js/src/cleantalk-admin-settings-page.js @@ -705,7 +705,7 @@ function onApbctCookieTypeChange(event) { // eslint-disable-line no-unused-vars __('Attention!', 'cleantalk-spam-protect'), ( __( - 'Cache solutions detected. ', + 'Cache-problem solutions detected in the environment. ', 'cleantalk-spam-protect', ) + __( diff --git a/js/src/public-1-functions.js b/js/src/public-1-functions.js index 88ce4356f..e32ba7998 100644 --- a/js/src/public-1-functions.js +++ b/js/src/public-1-functions.js @@ -98,7 +98,7 @@ function ctSetCookie( cookies, value, expires='') { let listOfCookieNamesToForceAlt = [ 'ct_sfw_pass_key', 'ct_sfw_passed', - 'wordpress_apbct_antibot', + 'apbct_antibot', 'apbct_anticrawler_passed', 'apbct_bot_detector_exist', 'apbct_antiflood_passed', @@ -487,6 +487,15 @@ function getNoCookieData() { // eslint-disable-line no-unused-vars let noCookieDataLocal = apbctLocalStorage.getCleanTalkData(); let noCookieDataSession = apbctSessionStorage.getCleanTalkData(); let noCookieData = {...noCookieDataLocal, ...noCookieDataSession}; + + // Bot detector browser state is transferred with the hidden field on the NoCookie mode + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + noCookieData[browserState.key] = browserState.value; + } + } + noCookieData = JSON.stringify(noCookieData); return '_ct_no_cookie_data_' + btoa(unescape(encodeURIComponent(noCookieData))); @@ -514,7 +523,21 @@ function getCleanTalkStorageDataArray() { // eslint-disable-line no-unused-vars noCookieDataFromUserActivity = {collecting_user_activity_data: collectingUserActivityData}; } - return {...noCookieDataLocal, ...noCookieDataSession, ...noCookieDataTypo, ...noCookieDataFromUserActivity}; + let browserStateData = {}; + if (typeof apbctGetBrowserStatePair === 'function') { + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + browserStateData[browserState.key] = browserState.value; + } + } + + return { + ...noCookieDataLocal, + ...noCookieDataSession, + ...noCookieDataTypo, + ...noCookieDataFromUserActivity, + ...browserStateData, + }; } /** diff --git a/js/src/public-1-main.js b/js/src/public-1-main.js index 1a2ec6d1a..4740e6586 100644 --- a/js/src/public-1-main.js +++ b/js/src/public-1-main.js @@ -590,6 +590,9 @@ class ApbctHandler { const eventTokenKey = useUnwrappedCleantalkKeys ? 'ct_bot_detector_event_token' : 'data%5Bct_bot_detector_event_token%5D'; + const browserStateKey = useUnwrappedCleantalkKeys ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; if (!( +ctPublic.bot_detector_enabled && @@ -614,6 +617,12 @@ class ApbctHandler { } } + const browserState = apbctGetBrowserStatePair(); + if (browserState && body.indexOf('apbct_browser_state') === -1) { + addidionalCleantalkData += '&' + browserStateKey + '=' + + encodeURIComponent(browserState.value); + } + body += addidionalCleantalkData; } @@ -630,6 +639,11 @@ class ApbctHandler { body.append('ct_bot_detector_event_token', eventToken); } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState && !body.has(browserState.key)) { + body.append(browserState.key, browserState.value); + } } if (isNeedToAddCleantalkDataCheckJsonData) { @@ -667,6 +681,22 @@ class ApbctHandler { } } } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + try { + const bodyObj = JSON.parse(body); + if ( + bodyObj && typeof bodyObj === 'object' && + !Object.prototype.hasOwnProperty.call(bodyObj, browserState.key) + ) { + bodyObj[browserState.key] = browserState.value; + body = JSON.stringify(bodyObj); + } + } catch (e) { + // body is not JSON — leave as is + } + } } return originalSend.apply(this, [body]); @@ -724,6 +754,11 @@ class ApbctHandler { } else { args[1].body.append('ct_no_cookie_hidden_field', getNoCookieData()); } + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + args[1].body.append(browserState.key, browserState.value); + } } } } catch (e) { @@ -780,6 +815,22 @@ class ApbctHandler { * @return {string|FormData} Modified body. */ const attachFieldsToBody = function(body, fieldPair = false) { + const fieldPairs = [fieldPair, apbctGetBrowserStatePair()]; + + for (const pair of fieldPairs) { + body = attachFieldPairToBody(body, pair); + } + + return body; + }; + + /** + * Attach a single key/value pair to fetch request body + * @param {string|FormData} body Fetch request data body. + * @param {object|bool} fieldPair Key value to inject. + * @return {string|FormData} Modified body. + */ + const attachFieldPairToBody = function(body, fieldPair = false) { if (fieldPair) { if (body instanceof FormData || typeof body.append === 'function') { body.append(fieldPair.key, fieldPair.value); @@ -1076,11 +1127,15 @@ class ApbctHandler { const batchPayload = JSON.parse(args[1].body); if (batchPayload.requests && Array.isArray(batchPayload.requests)) { const fieldPair = selectFieldsData(+ctPublic.bot_detector_enabled); + const browserState = apbctGetBrowserStatePair(); for (const req of batchPayload.requests) { const isAddItem = req.path === '/wc/store/v1/cart/add-item'; if (isAddItem && req.body && fieldPair && fieldPair.key) { req.body[fieldPair.key] = fieldPair.value; } + if (isAddItem && req.body && browserState) { + req.body[browserState.key] = browserState.value; + } } args[1].body = JSON.stringify(batchPayload); } @@ -1104,188 +1159,970 @@ class ApbctHandler { } /** - * Prepare jQuery.ajaxSetup to add nocookie data to the jQuery ajax request. + * Prepare jQuery.ajaxPrefilter to add CleanTalk data to jQuery ajax requests. * Notes: - * - Do it just once, the ajaxSetup.beforeSend will be overwritten for any calls. - * - Signs of forms need to be caught will be checked during ajaxSetup.settings.data process on send. + * - ajaxSetup.beforeSend is not used: a request can supply its own beforeSend and drop the default. + * - ajaxPrefilter runs for every jQuery ajax call after options are merged, so injection is guaranteed. + * - Form signs are checked on the request data/url at send time. * - Any sign of the form HTML of the caller is insignificant in this process. * - This is the only place where we can found hard dependency on jQuery, if the form use it - the script * will work independing if jQuery is loaded by CleanTalk or not * @return {void} */ catchJqueryAjax() { - if ( typeof jQuery !== 'undefined') { - // this code run on base ajax rules - so do not work due scripts use it's own ajax object injections - if ( typeof jQuery.ajaxSetup === 'function' ) { - jQuery.ajaxSetup({ - beforeSend: function(xhr, settings) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(settings, 'ajaxSetup'); - if (sourceSign.found !== false) { - settings.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, settings.data); - } - }, - }); + if ( typeof jQuery !== 'undefined' && typeof jQuery.ajaxPrefilter === 'function' ) { + jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { + const handler = new ApbctHandler(); + const sourceSign = handler.searchSignsForJQAjaxInjection(options, originalOptions); + if (sourceSign.found !== false) { + options.data = handler.injectCleantalkDataToJQAjax( + sourceSign, + handler.getJQAjaxPayloadForInject(options, originalOptions), + options, + ); + } + }); + } + } + + /** + * jQuery.param() on URLSearchParams/FormData can collapse options.data to "". + * Sign search already falls back to originalOptions; inject must use that payload too. + * @param {object} options + * @param {object=} originalOptions + * @return {*} + */ + getJQAjaxPayloadForInject(options, originalOptions) { + const current = options && options.data; + const original = originalOptions && originalOptions.data; + if ( this.jqAjaxPayloadWasCollapsed(current, original) ) { + return original; + } + return current; + } + + /** + * @param {*} current + * @param {*} original + * @return {boolean} + */ + jqAjaxPayloadWasCollapsed(current, original) { + if ( original === null || typeof original === 'undefined' ) { + return false; + } + if ( current === original ) { + return false; + } + const currentEmpty = current === '' || current === null || typeof current === 'undefined'; + if ( !currentEmpty ) { + return false; + } + if ( typeof original === 'string' ) { + return original !== ''; + } + return this.isJQAjaxFormData(original) || + this.isJQAjaxURLSearchParams(original) || + this.isJQAjaxPlainObjectOrArray(original); + } + + /** + * Normalize jQuery ajax data to a query string for sign search. + * Objects and serializeArray are read structurally so search never calls jQuery.param. + * Also reads known sign fields from the URL (IE11 FormData cannot be enumerated). + * @param {object} ajaxObject Ajax options object. + * @return {string} + */ + getJQAjaxDataAsString(ajaxObject) { + if ( !ajaxObject || typeof ajaxObject !== 'object' ) { + return ''; + } + let fromData = ''; + if ( typeof ajaxObject.data === 'string' ) { + fromData = ajaxObject.data; + } else if ( this.isJQAjaxPlainObjectOrArray(ajaxObject.data) ) { + fromData = this.getStructuredJQAjaxSignString(ajaxObject.data); + } else if ( this.isJQAjaxURLSearchParams(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } else if ( this.isJQAjaxFormData(ajaxObject.data) ) { + fromData = this.collectKnownSignStringFromKeyValueBag(ajaxObject.data); + } + // Native IE11 FormData is write-only (no get/forEach/entries). Signs then come from the URL. + const fromUrl = this.collectKnownSignStringFromUrl(ajaxObject.url); + if ( fromData && fromUrl ) { + return fromData + '&' + fromUrl; + } + return fromData || fromUrl; + } + + /** + * Build a sign string from top-level fields without serializing the whole payload. + * @param {object|Array} data + * @return {string} + */ + getStructuredJQAjaxSignString(data) { + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return this.getSerializeArraySignString(data); + } + const parts = []; + const action = this.getPlainObjectSignField(data, 'action'); + if ( typeof action === 'string' && action !== '' ) { + parts.push('action=' + action); + } + const nonce = this.getPlainObjectSignField(data, 'ur_frontend_form_nonce'); + if ( nonce !== null ) { + parts.push('ur_frontend_form_nonce=' + nonce); + } + if ( this.plainObjectHasTwtCcSignup(data) ) { + parts.push('twt_cc_signup=1'); + } + return parts.join('&'); + } + + /** + * Read action/nonce from top-level, data[key], or nested data.key. + * @param {object} data + * @param {string} key + * @return {string|number|null} + */ + getPlainObjectSignField(data, key) { + if ( !data || typeof data !== 'object' ) { + return null; + } + if ( this.isJQAjaxScalarSignValue(data[key]) ) { + return data[key]; + } + const bracketKey = 'data[' + key + ']'; + if ( this.isJQAjaxScalarSignValue(data[bracketKey]) ) { + return data[bracketKey]; + } + if ( + data.data && + typeof data.data === 'object' && + Object.prototype.toString.call(data.data) !== '[object Array]' && + this.isJQAjaxScalarSignValue(data.data[key]) + ) { + return data.data[key]; + } + return null; + } + + /** + * @param {*} value + * @return {boolean} + */ + isJQAjaxScalarSignValue(value) { + return typeof value === 'string' || typeof value === 'number'; + } + + /** + * @param {object} data + * @param {number=} depth + * @return {boolean} + */ + plainObjectHasTwtCcSignup(data, depth) { + if ( !data || typeof data !== 'object' ) { + return false; + } + if ( typeof depth === 'undefined' ) { + depth = 0; + } + if ( depth > 2 ) { + return false; + } + for ( const key in data ) { + if ( !Object.prototype.hasOwnProperty.call(data, key) ) { + continue; } - // this code run on ANY ajax on ANY script queue status - // todo Probably move all ajaxSetup actions to ajaxPrefilter - if ( typeof jQuery.ajaxPrefilter === 'function' ) { - jQuery.ajaxPrefilter(function(options, originalOptions, jqXHR) { - const handler = new ApbctHandler(); - const sourceSign = handler.searchSignsForJQAjaxInjection(options, 'ajaxPrefilter'); - if (sourceSign.found !== false) { - if (typeof options.data === 'string') { - options.data = handler.injectCleantalkDataToJQAjaxString(sourceSign, options.data); - } - if ( - typeof options.data === 'object' && - typeof options.data.append === 'function' - ) { - options.data = handler.injectCleantalkDataToJQAjaxFormData(sourceSign, options.data); - } - } - }); + const normalizedKey = this.unwrapJQAjaxFormDataKey(key); + if ( normalizedKey === 'twt_cc_signup' || key.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + const value = data[key]; + if ( typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1 ) { + return true; + } + if ( + value && + typeof value === 'object' && + Object.prototype.toString.call(value) !== '[object Array]' + ) { + if ( this.plainObjectHasTwtCcSignup(value, depth + 1) ) { + return true; + } + } + } + return false; + } + + /** + * @param {Array} entries + * @return {string} + */ + getSerializeArraySignString(entries) { + const parts = []; + for ( let i = 0; i < entries.length; i++ ) { + const entry = entries[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + continue; + } + const value = entry.value; + const normalizedKey = this.unwrapJQAjaxFormDataKey(entry.name); + if ( this.isJQAjaxKnownSignField(normalizedKey, value) ) { + parts.push(normalizedKey + '=' + value); + } + } + return parts.join('&'); + } + + /** + * True for serializeArray payloads, including an empty array. + * @param {Array} data + * @return {boolean} + */ + isJQAjaxSerializeArray(data) { + if ( Object.prototype.toString.call(data) !== '[object Array]' ) { + return false; + } + for ( let i = 0; i < data.length; i++ ) { + const entry = data[i]; + if ( !entry || typeof entry !== 'object' || typeof entry.name !== 'string' ) { + return false; + } + } + return true; + } + + /** + * Cross-realm URLSearchParams (instanceof fails across windows). + * @param {*} data + * @return {boolean} + */ + isJQAjaxURLSearchParams(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object URLSearchParams]' ) { + return true; + } + if ( tag === '[object FormData]' ) { + return false; + } + return typeof data.sort === 'function' && typeof data.get === 'function'; + } + + /** + * Cross-realm FormData, including common polyfills. + * @param {*} data + * @return {boolean} + */ + isJQAjaxFormData(data) { + if ( !data || typeof data !== 'object' || typeof data.append !== 'function' ) { + return false; + } + if ( this.isJQAjaxPlainObjectOrArray(data) || this.isJQAjaxURLSearchParams(data) ) { + return false; + } + const tag = Object.prototype.toString.call(data); + if ( tag === '[object FormData]' ) { + return true; + } + if ( tag === '[object Headers]' || typeof data.getSetCookie === 'function' ) { + return false; + } + return typeof data.forEach === 'function' || + typeof data.get === 'function' || + typeof data.entries === 'function'; + } + + /** + * Collect only known sign fields from FormData / URLSearchParams. + * Unwrap data[action] so later action=... checks match. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + collectKnownSignStringFromKeyValueBag(bag) { + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' ) { + return; + } + const valueAsString = String(value); + const normalizedKey = unwrapKey(key); + if ( + knownKeys[normalizedKey] || + valueAsString.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + valueAsString); + } + }); + if ( collected ) { + return parts.join('&'); + } + if ( typeof bag.get !== 'function' ) { + return ''; + } + const keysToProbe = [ + 'action', + 'ur_frontend_form_nonce', + 'twt_cc_signup', + ]; + const getParts = []; + for ( let i = 0; i < keysToProbe.length; i++ ) { + const key = keysToProbe[i]; + const value = this.getFormDataScalarValue(bag, [key, 'data[' + key + ']']); + if ( value !== null ) { + getParts.push(key + '=' + value); + } + } + return getParts.join('&'); + } + + /** + * Known sign fields from a request URL query. IE11-safe (no URLSearchParams). + * @param {string} url + * @return {string} + */ + collectKnownSignStringFromUrl(url) { + if ( typeof url !== 'string' || url === '' ) { + return ''; + } + const queryIndex = url.indexOf('?'); + if ( queryIndex === -1 || queryIndex === url.length - 1 ) { + return ''; + } + const hashIndex = url.indexOf('#', queryIndex); + const query = hashIndex === -1 ? + url.slice(queryIndex + 1) : + url.slice(queryIndex + 1, hashIndex); + const knownKeys = this.getJQAjaxKnownSignKeys(); + const unwrapKey = this.unwrapJQAjaxFormDataKey; + const parts = []; + const pairs = query.split('&'); + for ( let i = 0; i < pairs.length; i++ ) { + const pair = pairs[i]; + if ( !pair ) { + continue; + } + const eq = pair.indexOf('='); + let rawKey = eq === -1 ? pair : pair.slice(0, eq); + let rawValue = eq === -1 ? '' : pair.slice(eq + 1); + try { + rawKey = decodeURIComponent(rawKey.replace(/\+/g, ' ')); + rawValue = decodeURIComponent(rawValue.replace(/\+/g, ' ')); + } catch (e) { + continue; + } + const normalizedKey = unwrapKey(rawKey); + if ( + knownKeys[normalizedKey] || + rawValue.indexOf('twt_cc_signup') !== -1 || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + parts.push(normalizedKey + '=' + rawValue); + } + } + return parts.join('&'); + } + + /** + * Walk FormData/URLSearchParams via forEach, then entries() for polyfills that only have an iterator. + * @param {FormData|URLSearchParams} bag + * @param {Function} callback + * @return {boolean} + */ + forEachJQAjaxKeyValueBag(bag, callback) { + if ( typeof bag.forEach === 'function' ) { + try { + bag.forEach(callback); + return true; + } catch (e) { + // Fall through to entries(). + } + } + if ( typeof bag.entries !== 'function' ) { + return false; + } + try { + const iterator = bag.entries(); + if ( !iterator || typeof iterator.next !== 'function' ) { + return false; + } + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + callback(pair[1], pair[0]); + } + step = iterator.next(); + } + return true; + } catch (e) { + return false; + } + } + + /** + * @return {Object} + */ + getJQAjaxKnownSignKeys() { + const knownKeys = Object.create(null); + knownKeys.action = true; + knownKeys.ur_frontend_form_nonce = true; + knownKeys.twt_cc_signup = true; + return knownKeys; + } + + /** + * @param {string} normalizedKey + * @param {*} value + * @return {boolean} + */ + isJQAjaxKnownSignField(normalizedKey, value) { + if ( + normalizedKey === 'action' || + normalizedKey === 'ur_frontend_form_nonce' || + normalizedKey === 'twt_cc_signup' || + normalizedKey.indexOf('twt_cc_signup') !== -1 + ) { + return true; + } + return typeof value === 'string' && value.indexOf('twt_cc_signup') !== -1; + } + + /** + * Treat data[action] as action for WP-style payloads. + * @param {string} key + * @return {string} + */ + unwrapJQAjaxFormDataKey(key) { + if ( typeof key !== 'string' ) { + return ''; + } + if ( key.length > 6 && key.indexOf('data[') === 0 && key.charAt(key.length - 1) === ']' ) { + return key.slice(5, -1); + } + return key; + } + + /** + * @param {FormData} formData + * @param {Array.} keys + * @return {string|number|null} + */ + getFormDataScalarValue(formData, keys) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && (typeof value === 'string' || typeof value === 'number') ) { + return value; } } + return null; + } + + /** + * True for arrays and plain objects that jQuery.param can serialize safely. + * @param {*} data + * @return {boolean} + */ + isJQAjaxPlainObjectOrArray(data) { + if ( data === null || typeof data !== 'object' ) { + return false; + } + if ( Object.prototype.toString.call(data) === '[object Array]' ) { + return true; + } + if ( typeof jQuery !== 'undefined' && typeof jQuery.isPlainObject === 'function' ) { + return jQuery.isPlainObject(data); + } + const proto = Object.getPrototypeOf(data); + return proto === Object.prototype || proto === null; } /** * Search for sign within AJAX data to do inject CleanTalk data. * @param {object} ajaxObject Ajax object. - * @param {string} catchOn Function should be catched on. + * @param {object=} originalOptions Original jQuery ajax options before merge. * @return {{found: boolean, keepUnwrapped: boolean, attachVisibleFieldsData: boolean}} */ - searchSignsForJQAjaxInjection(ajaxObject, catchOn = 'ajaxSetup') { + searchSignsForJQAjaxInjection(ajaxObject, originalOptions) { let sourceSign = { 'found': false, 'keepUnwrapped': false, 'attachVisibleFieldsData': false, }; - // on ajaxSetup - if (catchOn === 'ajaxSetup') { - // settings data is string (important!) - if ( typeof ajaxObject.data === 'string' ) { - if ( - ajaxObject.data.indexOf('action=fl_builder_subscribe_form_submit') !== -1 - ) { - sourceSign.found = 'fl_builder_subscribe_form_submit'; - } - if ( - ajaxObject.data.indexOf('twt_cc_signup') !== -1 - ) { - sourceSign.found = 'twt_cc_signup'; - } - if ( - ajaxObject.data.indexOf('action=mailpoet') !== -1 - ) { - sourceSign.found = 'action=mailpoet'; - sourceSign.attachVisibleFieldsData = true; - } + let dataString = this.getJQAjaxDataAsString(ajaxObject); + if ( !dataString && originalOptions && originalOptions !== ajaxObject ) { + dataString = this.getJQAjaxDataAsString(originalOptions); + } - if ( - ajaxObject.data.indexOf('action=user_registration') !== -1 && - ajaxObject.data.indexOf('ur_frontend_form_nonce') !== -1 - ) { - sourceSign.found = 'action=user_registration'; - } + if ( dataString.indexOf('action=fl_builder_subscribe_form_submit') !== -1 ) { + sourceSign.found = 'fl_builder_subscribe_form_submit'; + } + if ( dataString.indexOf('twt_cc_signup') !== -1 ) { + sourceSign.found = 'twt_cc_signup'; + } + if ( dataString.indexOf('action=mailpoet') !== -1 ) { + sourceSign.found = 'action=mailpoet'; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=user_registration') !== -1 && + dataString.indexOf('ur_frontend_form_nonce') !== -1 + ) { + sourceSign.found = 'action=user_registration'; + } + if ( dataString.indexOf('action=happyforms_message') !== -1 ) { + sourceSign.found = 'action=happyforms_message'; + } + if ( dataString.indexOf('action=new_activity_comment') !== -1 ) { + sourceSign.found = 'action=new_activity_comment'; + } + if ( dataString.indexOf('action=wwlc_create_user') !== -1 ) { + sourceSign.found = 'action=wwlc_create_user'; + } + if ( dataString.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 ) { + sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=drplus_signup') !== -1 ) { + sourceSign.found = 'action=drplus_signup'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=bt_cc') !== -1 ) { + sourceSign.found = 'action=bt_cc'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=wpr_form_builder_email') !== -1 ) { + sourceSign.found = 'action=wpr_form_builder_email'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=nf_ajax_submit') !== -1 ) { + sourceSign.found = 'action=nf_ajax_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( + dataString.indexOf('action=uael_register_user') !== -1 && + ctPublic.data__cookies_type === 'none' + ) { + sourceSign.found = 'action=uael_register_user'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=SQBSubmitQuizAjax') !== -1 ) { + sourceSign.found = 'action=SQBSubmitQuizAjax'; + sourceSign.keepUnwrapped = true; + } + if ( dataString.indexOf('action=user_registration_user_form_submit') !== -1 ) { + sourceSign.found = 'action=user_registration_user_form_submit'; + sourceSign.keepUnwrapped = true; + sourceSign.attachVisibleFieldsData = true; + } + if ( dataString.indexOf('action=bloom_subscribe') !== -1 ) { + sourceSign.found = 'action=bloom_subscribe'; + sourceSign.keepUnwrapped = true; + } + if ( + this.isJQAjaxFormData(ajaxObject.data) && + typeof ajaxObject.data.get === 'function' && + ajaxObject.data.get('action') === 'pafe_ajax_form_builder' + ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } else if ( dataString.indexOf('action=pafe_ajax_form_builder') !== -1 ) { + sourceSign.found = 'action=pafe_ajax_form_builder'; + sourceSign.keepUnwrapped = true; + } - if (ajaxObject.data.indexOf('action=happyforms_message') !== -1) { - sourceSign.found = 'action=happyforms_message'; - } + // woocommerce add to cart is based on URL + if ( typeof ajaxObject.url === 'string' && ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1 ) { + sourceSign.found = 'wc-ajax=add_to_cart'; + // GET/HEAD: PHP reads Get::get('ct_bot_detector_event_token'), not data[...]. + if ( this.isJQAjaxNoContentMethod(ajaxObject) ) { + sourceSign.keepUnwrapped = true; + } + } - if ( - ajaxObject.data.indexOf('action=new_activity_comment') !== -1 - ) { - sourceSign.found = 'action=new_activity_comment'; - } - if ( - ajaxObject.data.indexOf('action=wwlc_create_user') !== -1 - ) { - sourceSign.found = 'action=wwlc_create_user'; - } - if ( - ajaxObject.data.indexOf('action=WPBC_AJX_BOOKING__CREATE') !== -1 - ) { - sourceSign.found = 'action=WPBC_AJX_BOOKING__CREATE'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; - } - if ( - ajaxObject.data.indexOf('action=drplus_signup') !== -1 - ) { - sourceSign.found = 'action=drplus_signup'; - sourceSign.keepUnwrapped = true; - } - if ( - ajaxObject.data.indexOf('action=bt_cc') !== -1 - ) { - sourceSign.found = 'action=bt_cc'; - sourceSign.keepUnwrapped = true; + return sourceSign; + } + + /** + * Inject CleanTalk data into jQuery ajax payload of any supported type. + * @param {object} sourceSign + * @param {*} ajaxData + * @param {object=} ajaxOptions jQuery ajax options (traditional, processData, contentType). + * Keep URLSearchParams/objects when processData or contentType is false. + * URLSearchParams must also disable processData, or jQuery.param() later yields "". + * GET/HEAD never keep the original type: jQuery only puts string data on the URL. + * @return {*} + */ + injectCleantalkDataToJQAjax(sourceSign, ajaxData, ajaxOptions) { + const traditional = ajaxOptions && ajaxOptions.traditional; + const keepOriginalType = !this.isJQAjaxNoContentMethod(ajaxOptions) && !!(ajaxOptions && ( + ajaxOptions.processData === false || + ajaxOptions.contentType === false + )); + + if ( ajaxData === null || typeof ajaxData === 'undefined' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ''); + } + if ( typeof ajaxData === 'string' ) { + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData); + } + if ( this.isJQAjaxPlainObjectOrArray(ajaxData) ) { + if ( keepOriginalType ) { + if ( Object.prototype.toString.call(ajaxData) === '[object Array]' ) { + if ( this.isJQAjaxSerializeArray(ajaxData) ) { + return this.injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData); + } + return ajaxData; } - if ( - ajaxObject.data.indexOf('action=wpr_form_builder_email') !== -1 - ) { - sourceSign.found = 'action=wpr_form_builder_email'; - sourceSign.keepUnwrapped = true; + return this.injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData); + } + try { + if ( typeof jQuery !== 'undefined' && typeof jQuery.param === 'function' ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + jQuery.param(ajaxData, traditional), + ); } - if ( - ajaxObject.data.indexOf('action=nf_ajax_submit') !== -1 - ) { - sourceSign.found = 'action=nf_ajax_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; + } catch (e) { + return ajaxData; + } + return ajaxData; + } + if ( this.isJQAjaxURLSearchParams(ajaxData) ) { + if ( keepOriginalType ) { + this.preserveJQAjaxURLSearchParamsOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxKeyValue( + sourceSign, + this.cloneURLSearchParams(ajaxData), + ); + } + return this.injectCleantalkDataToJQAjaxString(sourceSign, ajaxData.toString()); + } + if ( this.isJQAjaxFormData(ajaxData) ) { + if ( this.isJQAjaxNoContentMethod(ajaxOptions) ) { + return this.injectCleantalkDataToJQAjaxString( + sourceSign, + this.serializeJQAjaxKeyValueBag(ajaxData), + ); + } + this.preserveJQAjaxFormDataOptions(ajaxOptions); + return this.injectCleantalkDataToJQAjaxFormData( + sourceSign, + this.cloneFormData(ajaxData), + ); + } + return ajaxData; + } + + /** + * GET/HEAD have no body. Missing type is GET (jQuery default). + * @param {object=} ajaxOptions + * @return {boolean} + */ + isJQAjaxNoContentMethod(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return false; + } + const type = ajaxOptions.type || ajaxOptions.method; + if ( typeof type !== 'string' || type === '' ) { + return true; + } + const method = type.toUpperCase(); + return method === 'GET' || method === 'HEAD'; + } + + /** + * Collect CleanTalk fields to append to a key/value payload. + * @param {object} sourceSign + * @return {Array.>} + */ + getCleantalkJQAjaxFieldPairs(sourceSign) { + const pairs = []; + const wrapKey = function(key) { + return sourceSign.keepUnwrapped ? key : 'data[' + key + ']'; + }; + + if ( + +ctPublic.bot_detector_enabled && + apbctLocalStorage.get('bot_detector_event_token') + ) { + const token = this.toolGetEventToken(); + if ( token ) { + pairs.push([wrapKey('ct_bot_detector_event_token'), token]); + } + } else { + const noCookieData = getNoCookieData(); + if ( noCookieData ) { + pairs.push([wrapKey('ct_no_cookie_hidden_field'), noCookieData]); + } + } + + const browserState = apbctGetBrowserStatePair(); + if ( browserState ) { + const browserStateKey = sourceSign.keepUnwrapped ? + browserState.key : + 'data[' + browserState.key + ']'; + pairs.push([browserStateKey, browserState.value]); + } + + return pairs; + } + + /** + * jQuery.param(FormData) after the prefilter yields "". Keep the body as FormData. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxFormDataOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + ajaxOptions.contentType = false; + } + + /** + * jQuery.param(URLSearchParams) after the prefilter yields "". Keep the body as URLSearchParams. + * @param {object=} ajaxOptions + * @return {void} + */ + preserveJQAjaxURLSearchParamsOptions(ajaxOptions) { + if ( !ajaxOptions || typeof ajaxOptions !== 'object' ) { + return; + } + ajaxOptions.processData = false; + } + + /** + * Read a FormData field via get(), forEach(), or entries(). + * Native IE11 FormData is write-only and cannot be read. + * @param {FormData} formData + * @param {Array.} keys + * @return {*} + */ + getFormDataField(formData, keys) { + if ( typeof formData.get === 'function' ) { + for ( let i = 0; i < keys.length; i++ ) { + const value = formData.get(keys[i]); + if ( value !== null && typeof value !== 'undefined' ) { + return value; } - if ( - ajaxObject.data.indexOf('action=uael_register_user') !== -1 && - ctPublic.data__cookies_type === 'none' - ) { - sourceSign.found = 'action=uael_register_user'; - sourceSign.keepUnwrapped = true; + } + } + if ( typeof formData.forEach === 'function' ) { + let found = null; + formData.forEach(function(value, key) { + if ( found !== null ) { + return; } - if ( - ajaxObject.data.indexOf('action=SQBSubmitQuizAjax') !== -1 - ) { - sourceSign.found = 'action=SQBSubmitQuizAjax'; - sourceSign.keepUnwrapped = true; + for ( let i = 0; i < keys.length; i++ ) { + if ( key === keys[i] ) { + found = value; + return; + } } - if ( - ajaxObject.data.indexOf('action=user_registration_user_form_submit') !== -1 - ) { - sourceSign.found = 'action=user_registration_user_form_submit'; - sourceSign.keepUnwrapped = true; - sourceSign.attachVisibleFieldsData = true; + }); + if ( found !== null ) { + return found; + } + } + if ( typeof formData.entries === 'function' ) { + try { + const iterator = formData.entries(); + if ( iterator && typeof iterator.next === 'function' ) { + let step = iterator.next(); + while ( !step.done ) { + const pair = step.value; + if ( pair ) { + for ( let i = 0; i < keys.length; i++ ) { + if ( pair[0] === keys[i] ) { + return pair[1]; + } + } + } + step = iterator.next(); + } } + } catch (e) { + return null; + } + } + return null; + } + + /** + * Clone URLSearchParams so the caller's instance is not mutated. + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + cloneURLSearchParams(params) { + const serialized = typeof params.toString === 'function' ? params.toString() : ''; + if ( typeof params.constructor === 'function' && params.constructor !== Object ) { + try { + return new params.constructor(serialized); + } catch (e) { + // Fall through to the current-window constructor. + } + } + if ( typeof URLSearchParams === 'function' ) { + try { + return new URLSearchParams(serialized); + } catch (e) { + return params; + } + } + return params; + } + + /** + * Clone FormData when it can be enumerated (forEach or entries); otherwise reuse. + * @param {FormData} formData + * @return {FormData} + */ + cloneFormData(formData) { + try { + const clone = new FormData(); + const copied = this.forEachJQAjaxKeyValueBag(formData, function(value, key) { + clone.append(key, value); + }); + if ( copied ) { + return clone; } - // wooocommerce add to cart is based on URL - if ( typeof ajaxObject.url === 'string' ) { - if (ajaxObject.url.indexOf('wc-ajax=add_to_cart') !== -1) { - sourceSign.found = 'wc-ajax=add_to_cart'; + } catch (e) { + return formData; + } + return formData; + } + + /** + * Form-urlencoded string from FormData/URLSearchParams. Skip File/Blob values. + * @param {FormData|URLSearchParams} bag + * @return {string} + */ + serializeJQAjaxKeyValueBag(bag) { + const parts = []; + const collected = this.forEachJQAjaxKeyValueBag(bag, function(value, key) { + if ( typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean' ) { + return; + } + parts.push(encodeURIComponent(String(key)) + '=' + encodeURIComponent(String(value))); + }); + if ( collected ) { + return parts.join('&'); + } + return ''; + } + + /** + * Inject CleanTalk fields into URLSearchParams without changing the payload type. + * @param {object} sourceSign + * @param {URLSearchParams} params + * @return {URLSearchParams} + */ + injectCleantalkDataToJQAjaxKeyValue(sourceSign, params) { + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + params.append(pairs[i][0], pairs[i][1]); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( extractor ) { + const extracted = extractor.extract(params.toString()); + if ( typeof extracted === 'string' ) { + params.append('apbct_visible_fields', extracted); } } } + return params; + } - // on ajaxPrefilter - if (catchOn === 'ajaxPrefilter') { - if (typeof ajaxObject.data === 'string') { - if (ajaxObject.data.indexOf('action=bloom_subscribe') !== -1) { - sourceSign.found = 'action=bloom_subscribe'; - sourceSign.keepUnwrapped = true; + /** + * Inject CleanTalk fields into a jQuery serializeArray payload. + * @param {object} sourceSign + * @param {Array} ajaxData + * @return {Array} + */ + injectCleantalkDataToJQAjaxSerializeArray(sourceSign, ajaxData) { + const result = ajaxData.slice(); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result.push({ + name: pairs[i][0], + value: pairs[i][1], + }); + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); + if ( + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' + ) { + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.push({ + name: 'apbct_visible_fields', + value: extracted, + }); } } + } + return result; + } + /** + * Inject CleanTalk fields into a plain object without changing the payload type. + * @param {object} sourceSign + * @param {object} ajaxData + * @return {object} + */ + injectCleantalkDataToJQAjaxPlainObject(sourceSign, ajaxData) { + const result = typeof jQuery !== 'undefined' && typeof jQuery.extend === 'function' ? + jQuery.extend({}, ajaxData) : + this.clonePlainObject(ajaxData); + const pairs = this.getCleantalkJQAjaxFieldPairs(sourceSign); + for ( let i = 0; i < pairs.length; i++ ) { + result[pairs[i][0]] = pairs[i][1]; + } + if ( sourceSign.attachVisibleFieldsData ) { + const extractor = ApbctVisibleFieldsExtractor.createExtractor(sourceSign.found); if ( - typeof ajaxObject.data === 'object' && - ajaxObject.data !== null && - typeof ajaxObject.data.get === 'function' + extractor && + typeof jQuery !== 'undefined' && + typeof jQuery.param === 'function' ) { - if (ajaxObject.data.get('action') === 'pafe_ajax_form_builder') { - sourceSign.found = 'action=pafe_ajax_form_builder'; - sourceSign.keepUnwrapped = true; + const extracted = extractor.extract(jQuery.param(ajaxData)); + if ( typeof extracted === 'string' ) { + result.apbct_visible_fields = extracted; } } } + return result; + } - return sourceSign; + /** + * IE11-safe shallow copy of a plain object. + * @param {object} ajaxData + * @return {object} + */ + clonePlainObject(ajaxData) { + const result = {}; + for ( const key in ajaxData ) { + if ( Object.prototype.hasOwnProperty.call(ajaxData, key) ) { + result[key] = ajaxData[key]; + } + } + return result; } /** @@ -1297,8 +2134,7 @@ class ApbctHandler { injectCleantalkDataToJQAjaxFormData(sourceSign, ajaxDataFormData) { if ( typeof sourceSign !== 'object' || - typeof ajaxDataFormData !== 'object' || - !(ajaxDataFormData instanceof FormData) + !this.isJQAjaxFormData(ajaxDataFormData) ) { return ajaxDataFormData; } @@ -1329,6 +2165,16 @@ class ApbctHandler { } } + // Bot detector browser state + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + if (sourceSign.keepUnwrapped) { + ajaxDataFormData.append(browserState.key, browserState.value); + } else { + ajaxDataFormData.append('data[' + browserState.key + ']', browserState.value); + } + } + // Visible fields if (sourceSign.attachVisibleFieldsData) { let visibleFieldsSearchResult = false; @@ -1336,13 +2182,10 @@ class ApbctHandler { if (extractor) { // Try to find form_id in FormData to find form container and // collect visible fields only inside it - let formId = null; - for (let pair of ajaxDataFormData.entries()) { - if (pair[0] === 'form_id' || pair[0] === 'data[form_id]') { - formId = pair[1]; - break; - } - } + const formId = this.getFormDataField( + ajaxDataFormData, + ['form_id', 'data[form_id]'], + ); let container = null; if (formId && typeof formId === 'string') { // Sanitize formId to prevent selector injection @@ -1387,6 +2230,15 @@ class ApbctHandler { let eventToken = ''; let noCookieData = ''; let visibleFieldsString = ''; + let browserStateString = ''; + + const browserState = apbctGetBrowserStatePair(); + if (browserState) { + const browserStateKey = sourceSign.keepUnwrapped ? + 'apbct_browser_state' : + 'data%5Bapbct_browser_state%5D'; + browserStateString = browserStateKey + '=' + encodeURIComponent(browserState.value) + '&'; + } if ( +ctPublic.bot_detector_enabled && @@ -1403,9 +2255,9 @@ class ApbctHandler { } else { noCookieData = getNoCookieData(); if (sourceSign.keepUnwrapped) { - noCookieData = 'ct_no_cookie_hidden_field=' + noCookieData + '&'; + noCookieData = 'ct_no_cookie_hidden_field=' + encodeURIComponent(noCookieData) + '&'; } else { - noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + noCookieData + '&'; + noCookieData = 'data%5Bct_no_cookie_hidden_field%5D=' + encodeURIComponent(noCookieData) + '&'; } } @@ -1428,7 +2280,7 @@ class ApbctHandler { } } - return noCookieData + eventToken + visibleFieldsString + ajaxDataString; + return noCookieData + eventToken + browserStateString + visibleFieldsString + ajaxDataString; } /** diff --git a/js/src/public-3-bot-detector-log.js b/js/src/public-3-bot-detector-log.js index 6630a29e6..1877b3ff0 100644 --- a/js/src/public-3-bot-detector-log.js +++ b/js/src/public-3-bot-detector-log.js @@ -1,61 +1,120 @@ -let botDetectorLogLastUpdate = 0; -let botDetectorLogEventTypesCollected = []; - -// bot_detector frontend_data log alt session saving cron -if ( - ctPublicFunctions.hasOwnProperty('bot_detector_enabled') && - +ctPublicFunctions.bot_detector_enabled && - ctPublicFunctions.hasOwnProperty('data__frontend_data_log_enabled') && - ctPublicFunctions.data__frontend_data_log_enabled == 1 -) { - sendBotDetectorLogToAltSessions(1000); -} - /** - * Send BotDetector logs data to alternative sessions. - * If log_last_update has changed and log contains new event types, the log will be sent to the alternative sessions. - * @param {int} cronStartTimeout delay before cron start - * @param {int} interval check fires on interval + * Bot detector browser state. + * + * The state is passed to the site backend with the current JS->PHP transport and goes + * to the moderate request as sender_info.bot_detector_frontend_data_log. */ -function sendBotDetectorLogToAltSessions(cronStartTimeout = 3000, interval = 1000) { - setTimeout(function() { - setInterval(function() { - const currentLog = apbctLocalStorage.get('ct_bot_detector_frontend_data_log'); - if (needsSaveLogToAltSessions(currentLog)) { - botDetectorLogLastUpdate = currentLog.log_last_update; - // the log will be taken from javascriptclientdata - ctSetAlternativeCookie([], {forceAltCookies: true}); +class ApbctBrowserState { + static STATE_KEY = 'apbct_browser_state'; + static LOG_KEY = 'ct_bot_detector_frontend_data_log'; + static SCRIPT_SIGNS = { + botd_wrapper_loaded: 'ct-bot-detector-wrapper', + botd_logic_loaded: 'ct-bot-detector.min', + }; + /** + * This LS key is set on bot-detector side + * @type {string} + */ + static TRANSPORT_ENABLED_SIGN_KEY = 'bot_detector_log_transport_enabled'; + static botdWrapperLoaded = 0; + static botdLogicLoaded = 0; + + /** + * Get the current browser state as a JSON string ready to be transferred. + * @return {string} Empty string if the bot detector is disabled or on any collecting error. + */ + static getFrontendDataLog() { + const prefix = (typeof ctPublicFunctions !== 'undefined' && ctPublicFunctions.cookiePrefix) ? + ctPublicFunctions.cookiePrefix : + ''; + const logKey = prefix + ApbctBrowserState.LOG_KEY; + const noPrefixLogKey = ApbctBrowserState.LOG_KEY; + + if (typeof apbctLocalStorage !== 'undefined' && apbctLocalStorage.get) { + const logObject = apbctLocalStorage.get(logKey) || apbctLocalStorage.get(noPrefixLogKey) || null; + if (logObject && typeof logObject === 'string') { + try { + return JSON.parse(logObject); + } catch (e) { + return ''; + } } - }, interval); - }, cronStartTimeout); + return logObject; + } + + let rawLog = localStorage.getItem(logKey); + if (!rawLog) { + rawLog = localStorage.getItem(noPrefixLogKey) || null; + } + + try { + return typeof rawLog === 'string' ? JSON.parse(rawLog) : rawLog; + } catch (e) { + return ''; + } + } + + /** + * + * @return {object} + */ + static asDTO() { + return { + botd_logic_loaded: ApbctBrowserState.botdLogicLoaded, + botd_wrapper_loaded: ApbctBrowserState.botdWrapperLoaded, + frontend_data_log: '', + transport_enabled: 1, + }; + } + + /** + * Look for the bot detector scripts in the page DOM. + * @return {boolean} True if both scripts are found. + */ + static detectScripts() { + if (ApbctBrowserState.botdWrapperLoaded && ApbctBrowserState.botdLogicLoaded) { + return true; + } + + const scripts = document.getElementsByTagName('script'); + + for (let i = 0; i < scripts.length; i++) { + const src = scripts[i].getAttribute('src'); + if (!src) { + continue; + } + if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_wrapper_loaded) !== -1) { + ApbctBrowserState.botdWrapperLoaded = 1; + } else if (src.indexOf(ApbctBrowserState.SCRIPT_SIGNS.botd_logic_loaded) !== -1) { + ApbctBrowserState.botdLogicLoaded = 1; + } + } + + // The bot detector logic sets this flag on its own start + return !!ApbctBrowserState.botdWrapperLoaded && !!ApbctBrowserState.botdLogicLoaded; + } } /** - * Check if the log needs to be saved to the alt sessions. If the log has new event types, it will be saved. - * @param {object} currentLog - * @return {boolean} + * Get the browser state as a key/value pair to attach it to an intercepted request. + * @return {{key: string, value: string}|false} False if there is nothing to attach. */ -function needsSaveLogToAltSessions(currentLog) { - if ( - currentLog && currentLog.hasOwnProperty('log_last_update') && - botDetectorLogLastUpdate !== currentLog.log_last_update - ) { - try { - for (let i = 0; i < currentLog.records.length; i++) { - const currentType = currentLog.records[i].frontend_data.js_event; - // check if this event type was already collected - if (currentType !== undefined && botDetectorLogEventTypesCollected.includes(currentType)) { - continue; - } - // add new event type to collection, this type will be sent to the alt sessions further - botDetectorLogEventTypesCollected.push(currentType); - return true; +function apbctGetBrowserStatePair() { // eslint-disable-line no-unused-vars + try { + ApbctBrowserState.detectScripts(); + let state = ApbctBrowserState.asDTO(); + if ( ApbctBrowserState.botdLogicLoaded ) { + const transportEnabled = localStorage.getItem(ApbctBrowserState.TRANSPORT_ENABLED_SIGN_KEY) === '1'; + if (transportEnabled) { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); + } else { + state.transport_enabled = 0; } - } catch (e) { - console.log('APBCT: bot detector log collection error: ' . e.toString()); + } else { + state.frontend_data_log = ApbctBrowserState.getFrontendDataLog(); } + return {key: ApbctBrowserState.STATE_KEY, value: JSON.stringify(state)}; + } catch (e) { + return false; } - return false; } - - diff --git a/lib/Cleantalk/Antispam/IntegrationMetrics/IMetricDTO.php b/lib/Cleantalk/Antispam/IntegrationMetrics/IMetricDTO.php new file mode 100644 index 000000000..0716c34fc --- /dev/null +++ b/lib/Cleantalk/Antispam/IntegrationMetrics/IMetricDTO.php @@ -0,0 +1,210 @@ + + * $dto = new IMetricDTO(); + * $dto->integration_name = 'WooCommerce'; + * $dto->custom_fields['order_count'] = 5; + * + * $json = $dto->getJSON(); + * // Send $json to analytics backend + * + * + * @see IMetricService for metric lifecycle management + * @see IMetricDTOTrait for integration with IntegrationBase and IntegrationByClassBase + */ +class IMetricDTO +{ + /** + * Name of the integration being measured (e.g., 'WooCommerce', 'NinjaForms'). + * Set by IMetricService::getDTO() when creating a new DTO instance. + * + * @var string + * @psalm-suppress PossiblyUnusedProperty + */ + public $integration_name = 'unset'; + + /** + * Version of the metrics schema/format. + * Can be overridden via IMetricDTOTrait::$imetric_dto_version on the integration class. + * + * @var string + * @psalm-suppress PossiblyUnusedProperty + */ + public $dto_version = '1.0.0'; + + /** + * Peak memory usage difference in kilobytes (KB) during integration processing. + * Calculated as: peak_memory_at_end - peak_memory_on_start + * Set during IMetricService::finalizeDTO() + * + * @var int + * @psalm-suppress PossiblyUnusedProperty + */ + public $peak_memory_diff_kb = 0; + + /** + * Total execution time in milliseconds (ms) for the entire integration processing. + * Calculated as: end_time_ms - timer_on_start_msec + * Set during IMetricService::finalizeDTO() + * + * @var int + * @psalm-suppress PossiblyUnusedProperty + */ + public $total_exec_time_ms = 0; + + /** + * Custom performance fields added by the integration. + * Format: field_name => field_value + * Example: ['form_fields_count' => 15, 'validation_passed' => true] + * Populated via IMetricService::setCustomField() + * + * @var array + * @psalm-suppress PossiblyUnusedProperty + */ + public $custom_fields = array(); + + /** + * Named time spans tracking specific operations within the integration. + * Format: span_name => ['time_msec' => float, 'memory_kb' => float, 'memory_peak_kb' => float, 'released' => bool] + * + * Each span captures: + * - time_msec: Duration in milliseconds (calculated by IMetricService::lease()) + * - memory_kb: Memory usage in KB (calculated by IMetricService::lease()) + * - memory_peak_kb: Peak memory in KB (calculated by IMetricService::lease()) + * - released: Whether the span has been finalized (true = measurements complete) + * + * Spans are created via IMetricService::seek() and finalized via IMetricService::lease() + * + * @var array + */ + public $spans = array(); + + /** + * Peak memory usage in KB for specific variable groups, tracked by span name. + * Format: span_name => peak_kb_value + * Example: ['form_data_vars' => 42.5, 'post_data_vars' => 128.3] + * Populated via IMetricService::dumpVarsSize() + * + * @var array + * @psalm-suppress PossiblyUnusedProperty + */ + public $variable_peak_kb = array(); + + /** + * Internal: Timer value (in ms) captured at metric start. + * Used to calculate total_exec_time_ms = current_time - timer_on_start_msec + * Set by IMetricService::startGlobalSeeking() and should not be modified directly. + * Excluded from JSON output via getArray() + * + * @var int + */ + public $timer_on_start_msec = 0; + + /** + * Internal: Memory usage (in KB) captured at metric start. + * Used to track relative memory usage throughout integration processing. + * Set by IMetricService::startGlobalSeeking() and should not be modified directly. + * Excluded from JSON output via getArray() + * + * @var int + * @psalm-suppress PossiblyUnusedProperty + */ + public $memory_usage_on_start_kb = 0; + + /** + * Internal: Peak memory usage (in KB) captured at metric start. + * Used to calculate peak_memory_diff_kb = peak_memory_at_end - peak_memory_on_start_kb + * Set by IMetricService::startGlobalSeeking() and should not be modified directly. + * Excluded from JSON output via getArray() + * + * @var int + */ + public $peak_memory_on_start_kb = 0; + + /** + * Internal: Flag indicating whether metric finalization is complete. + * When true, no further span creation or field updates are allowed. + * Set by IMetricService::finalizeDTO() + * Excluded from JSON output via getArray() + * + * @var bool + */ + public $is_released = false; + + /** + * JSON key name used when embedding this DTO in sender info. + * Used to identify metric data in analytics payloads. + * + * @var string + */ + public static $SENDER_INFO_KEY = 'imetric'; + + /** + * Serializes the DTO to JSON string. + * + * Converts the DTO object to a JSON-encoded string suitable for transmission to analytics systems. + * Internally calls getArray() to filter out internal properties before encoding. + * + * @return false|string JSON string representation of the DTO, or false if JSON encoding fails + * + * @see getArray() for the exact properties included in the output + */ + public function getJSON() + { + return @json_encode($this->getArray()); + } + + /** + * Returns the DTO as an associative array, excluding internal properties. + * + * This method filters out internal tracking properties that are not meant to be transmitted: + * - is_released: tracks finalization state + * - peak_memory_on_start_kb: baseline for calculations + * - memory_usage_on_start_kb: baseline for calculations + * - timer_on_start_msec: baseline for calculations + * - SENDER_INFO_KEY: static metadata key + * + * All other public properties are included in the output array. + * + * Usage: + * + * $dto = new IMetricDTO(); + * $dto->integration_name = 'MyForm'; + * $dto->custom_fields['status'] = 'success'; + * + * $array = $dto->getArray(); + * // $array now contains integration_name, dto_version, spans, custom_fields, etc. + * // but not is_released or *_on_start_* properties + * + * + * @return array Associative array of DTO properties ready for JSON serialization + * + * @see getJSON() for JSON-encoded output + */ + public function getArray() + { + $skip_properties = array( + 'is_released', + 'peak_memory_on_start_kb', + 'memory_usage_on_start_kb', + 'timer_on_start_msec', + 'SENDER_INFO_KEY' + ); + return array_map(function ($value) { + return $value; + }, array_diff_key(get_object_vars($this), array_flip($skip_properties))); + } +} diff --git a/lib/Cleantalk/Antispam/IntegrationMetrics/IMetricDTOTrait.php b/lib/Cleantalk/Antispam/IntegrationMetrics/IMetricDTOTrait.php new file mode 100644 index 000000000..a6da6d538 --- /dev/null +++ b/lib/Cleantalk/Antispam/IntegrationMetrics/IMetricDTOTrait.php @@ -0,0 +1,128 @@ + + * class MyIntegration extends IntegrationBase { + * use IMetricDTOTrait; // Already included in base class + * + * public function __construct() { + * $this->imetric_dto_version = '2.1.0'; // Override schema version if needed + * } + * } + * + * $integration = new MyIntegration(); + * $dto = IMetricService::getDTO($integration); + * $integration->setIMetricDTO($dto); + * // Now metrics can be collected via IMetricService + * + * + * @see IntegrationBase + * @see IntegrationByClassBase + * @see IMetricService + */ +trait IMetricDTOTrait +{ + /** + * Stores the metrics DTO instance for this integration. + * Access via getIMetricDTO() method. + * Should not be accessed directly - use getter/setter methods instead. + * + * @var IMetricDTO|null + */ + protected $imetric_dto = null; + + /** + * Custom schema version for the metrics DTO. + * If set before calling setIMetricDTO(), this value will override the default DTO version. + * Useful for versioning different integration metrics implementations. + * + * Default: null (uses IMetricDTO default version) + * + * Example: + * + * $integration->imetric_dto_version = '2.5.0'; + * IMetricService::getDTO($integration); // Will set dto_version to '2.5.0' + * + * + * @var string|null + */ + public $imetric_dto_version = null; + + /** + * Stores the provided IMetricDTO instance and applies version override if set. + * + * This method is called by IMetricService or integration setup code to assign + * a metrics DTO to this integration. If $imetric_dto_version is set on the integration, + * it will override the DTO's default version. + * + * Usage: + * + * $dto = new IMetricDTO(); + * $dto->integration_name = 'WooCommerce'; + * $integration->setIMetricDTO($dto); + * // Now $integration->getIMetricDTO() returns the same DTO + * + * + * @param IMetricDTO $imetric_dto The metrics DTO instance to store + * + * @return void + */ + public function setIMetricDTO(IMetricDTO $imetric_dto): void + { + $this->imetric_dto = $imetric_dto; + // Apply version override if the integration specifies a custom version + if (isset($this->imetric_dto_version)) { + $this->imetric_dto->dto_version = $this->imetric_dto_version; + } + } + + /** + * Retrieves the stored IMetricDTO instance. + * + * Returns the metrics DTO that was previously set via setIMetricDTO(), + * or null if no DTO has been assigned to this integration. + * + * Usage: + * + * $dto = $integration->getIMetricDTO(); + * if ($dto) { + * IMetricService::seek($integration, 'operation_name'); + * // ... perform operation ... + * IMetricService::lease($integration, 'operation_name'); + * } + * + * + * If the constant APBCT_SERVICE__DISABLE_INTEGRATION_METRICS is defined and true, + * this method will return null regardless of the stored DTO. + * + * @return IMetricDTO|null The stored metrics DTO, or null if not set + */ + public function getIMetricDTO() + { + if ($this->imetricIsDisabled()) { + return null; + } + return $this->imetric_dto; + } + + public function imetricIsDisabled(): bool + { + return Constant::is(Constant::APBCT_SERVICE__DISABLE_INTEGRATION_METRICS); + } +} diff --git a/lib/Cleantalk/Antispam/IntegrationMetrics/IMetricService.php b/lib/Cleantalk/Antispam/IntegrationMetrics/IMetricService.php new file mode 100644 index 000000000..c314f8de7 --- /dev/null +++ b/lib/Cleantalk/Antispam/IntegrationMetrics/IMetricService.php @@ -0,0 +1,458 @@ + + * // 1. Initialize metrics + * $integration = new MyIntegration(); + * $dto = IMetricService::getDTO($integration); + * if ($dto) { + * $integration->setIMetricDTO($dto); + * + * // 2. Record operations as spans + * IMetricService::seek($integration, 'form_validation'); + * // ... validate form fields ... + * IMetricService::lease($integration, 'form_validation'); + * + * // 3. Add custom data + * IMetricService::setCustomField($dto, 'field_count', count($fields)); + * IMetricService::dumpVarsSize($integration, ['data' => $data], 'data_size'); + * + * // 4. Finalize and retrieve metrics + * $json = IMetricService::finalizeDTO($integration); + * // Send $json to analytics backend + * } + * + * + * Integration Requirements: + * - Class must have $imetric_dto_version property set (or be null to skip metrics) + * - Class should use IMetricDTOTrait and extend IntegrationBase or IntegrationByClassBase + * + * @see IMetricDTO + * @see IMetricDTOTrait + */ +class IMetricService +{ + /** + * Creates and initializes a metrics DTO for an integration. + * + * Checks if the integration has enabled metrics (via $imetric_dto_version property). + * If enabled, creates a new IMetricDTO instance, sets the integration name from class name, + * and captures initial timing/memory values. + * + * This method should be called at the beginning of integration processing, + * typically before any metric collection begins. + * + * The integration_name is automatically extracted from the class name by removing + * the namespace, making it human-readable (e.g., '\Foo\Bar\WooCommerce' -> 'WooCommerce'). + * + * Usage: + * + * $dto = IMetricService::getDTO($integration); + * if ($dto) { + * $integration->setIMetricDTO($dto); + * // Metrics are now available for collection + * } else { + * // Integration doesn't have metrics enabled + * } + * + * + * @param IntegrationBase|IntegrationByClassBase $integration The integration instance + * + * @return IMetricDTO|false Initialized DTO if metrics are enabled, false otherwise + */ + public static function getDTO($integration) + { + $dto_version = self::getDTOVersion($integration); + if ($dto_version) { + $dto = new IMetricDTO(); + $dto->dto_version = $dto_version; + $full_class = get_class($integration); + $position = strrpos($full_class, '\\'); + if (!$position) { + $position = -1; + } + $dto->integration_name = substr($full_class, $position + 1); + self::startGlobalSeeking($dto); + return $dto; + } + return false; + } + + /** + * Checks if the integration has metrics enabled. + * + * Reads the $imetric_dto_version property. If it's set (not null) and truthy, + * metrics collection is enabled for this integration. + * + * @param IntegrationBase|IntegrationByClassBase $integration The integration instance + * + * @return string|false The DTO version string if enabled, false otherwise + */ + private static function getDTOVersion($integration) + { + return $integration->imetric_dto_version ?? false; + } + + /** + * Captures initial timing and memory values for metric tracking. + * + * Records the starting state of the system (current time, memory usage, peak memory). + * These baseline values are used later to calculate deltas (how much time and memory + * were consumed during integration processing). + * + * Called internally by getDTO() - do not call directly. + * + * @param IMetricDTO $dto The DTO to initialize + * + * @return void + */ + private static function startGlobalSeeking(IMetricDTO $dto) + { + $dto->timer_on_start_msec = self::getCurrentTimeMS(); + $dto->memory_usage_on_start_kb = self::getCurrentMemoryUsageKb(); + $dto->peak_memory_on_start_kb = self::getPeakMemoryUsageKb(); + } + + /** + * Gets the current system time in milliseconds. + * + * Uses microtime() for high precision timing. + * + * @return int Current time in milliseconds + */ + private static function getCurrentTimeMS() + { + return (int)(microtime(true) * 1000); + } + + /** + * Gets the current memory usage in kilobytes. + * + * Retrieves memory_get_usage() and converts to KB. + * + * @return int Current memory usage in KB + */ + private static function getCurrentMemoryUsageKb() + { + return (int)(memory_get_usage() / 1024); + } + + /** + * Gets the peak memory usage in kilobytes. + * + * Retrieves memory_get_peak_usage() and converts to KB. + * Note: Peak memory can only increase, never decrease during execution. + * + * @return int Peak memory usage in KB + */ + private static function getPeakMemoryUsageKb() + { + return (int)(memory_get_peak_usage() / 1024); + } + + /** + * Records the start of a named operation span. + * + * Creates a new span with the current timing and memory values. + * Spans track execution time and resource usage between seek() and lease(). + * Can only create each named span once - subsequent calls for the same span are ignored. + * + * Only works if: + * - Integration has a valid IMetricDTO + * - DTO has not been released (finalized) + * - Span name doesn't already exist + * + * Typical usage with lease(): + * + * IMetricService::seek($integration, 'database_query'); + * // ... execute database operations ... + * IMetricService::lease($integration, 'database_query'); + * // Now $dto->spans['database_query'] contains timing/memory delta + * + * + * @param IntegrationBase|IntegrationByClassBase $integration The integration instance + * @param string $span_name Unique name for this span (e.g., 'form_validation', 'user_check') + * + * @return void + */ + public static function seek($integration, string $span_name = 'undefined_span') + { + if ($integration instanceof IntegrationBase || $integration instanceof IntegrationByClassBase) { + $dto = $integration->getImetricDTO(); + if ($dto && !$dto->is_released) { + if (!isset($dto->spans[$span_name])) { + $dto->spans[$span_name] = [ + 'time_msec' => self::getCurrentTimeMS(), + 'memory_kb' => self::getCurrentMemoryUsageKb(), + 'memory_peak_kb' => self::getPeakMemoryUsageKb(), + 'released' => false + ]; + } + } + } + } + + /** + * Records the end of a named operation span and calculates deltas. + * + * Finalizes a span by: + * - Calculating elapsed time since seek() was called + * - Calculating memory delta + * - Calculating peak memory delta + * - Marking span as released (complete) + * + * Only works if: + * - Integration has a valid IMetricDTO + * - DTO has not been released + * - Span exists and has not been released yet + * + * If span doesn't exist or is already released, has no effect. + * + * After calling lease(), the span values contain: + * - time_msec: Time elapsed (milliseconds) + * - memory_kb: Memory delta (KB used during span) + * - memory_peak_kb: Peak memory delta (KB) + * - released: true (marks span as finalized) + * + * Usage: + * + * IMetricService::seek($integration, 'validation'); + * // ... perform validation (takes 50ms, uses 2MB) ... + * IMetricService::lease($integration, 'validation'); + * // Now: spans['validation']['time_msec'] ≈ 50 + * // spans['validation']['memory_kb'] ≈ 2048 + * + * + * @param IntegrationBase|IntegrationByClassBase $integration The integration instance + * @param string $span_name Name of the span to finalize + * + * @return void + */ + public static function lease($integration, string $span_name = 'undefined_span') + { + if ($integration instanceof IntegrationBase || $integration instanceof IntegrationByClassBase) { + $dto = $integration->getIMetricDTO(); + if ($dto && !$dto->is_released && isset($dto->spans[$span_name]) && is_array($dto->spans[$span_name])) { + $dto->spans[$span_name] = self::releaseSpan($dto->spans[$span_name]); + } + } + } + + /** + * Finalizes all open spans in a DTO. + * + * Iterates through all spans and calls releaseSpan() to finalize them. + * Spans that are already released are left unchanged. + * Typically called by finalizeDTO() as part of metric completion. + * + * @param IMetricDTO $dto The DTO containing spans to finalize + * + * @return void + */ + public static function releaseAllSpans(IMetricDTO $dto) + { + foreach ($dto->spans as $_span_name => &$span_content) { + $span_content = self::releaseSpan($span_content); + } + } + + /** + * Completes a single span by calculating deltas. + * + * Converts span values from absolute measurements to deltas: + * - time_msec: Changed from start_time to elapsed_time + * - memory_kb: Changed from start_memory to used_memory + * - memory_peak_kb: Changed from start_peak to peak_delta + * - released: Changed to true + * + * If span is already released, returns unchanged. + * If span is missing required fields, returns unchanged. + * + * Internal method called by lease() and releaseAllSpans() - typically not called directly. + * + * @param array $span_content The span data to finalize + * + * @return array Finalized span with delta values + */ + private static function releaseSpan(array $span_content) + { + if (isset( + $span_content['released'], + $span_content['time_msec'], + $span_content['memory_kb'], + $span_content['memory_peak_kb'] + ) + ) { + if (!$span_content['released']) { + $span_content['time_msec'] = self::getCurrentTimeMS() - $span_content['time_msec']; + $span_content['memory_kb'] = self::getCurrentMemoryUsageKb() - $span_content['memory_kb']; + $span_content['memory_peak_kb'] = self::getPeakMemoryUsageKb() - $span_content['memory_peak_kb']; + $span_content['released'] = true; + } + } + return $span_content; + } + + /** + * Completes metric collection and returns serialized JSON. + * + * This is the final step in metric lifecycle. It: + * 1. Finalizes all spans (calls releaseAllSpans()) + * 2. Calculates overall metrics: + * - peak_memory_diff_kb: Peak memory change during processing + * - total_exec_time_ms: Total elapsed time + * 3. Marks DTO as released (no further updates allowed) + * 4. Serializes to JSON + * + * If DTO is missing or already released, returns a default empty DTO as JSON. + * + * Should be called at the end of integration processing, typically in error handlers + * or finally blocks to ensure metrics are always captured. + * + * Complete usage pattern: + * + * try { + * $integration = new MyIntegration(); + * $dto = IMetricService::getDTO($integration); + * if ($dto) { + * $integration->setIMetricDTO($dto); + * // ... perform integration work ... + * } + * } finally { + * $metrics_json = IMetricService::finalizeDTO($integration); + * // Send metrics to backend + * $response->add_custom_data('metrics', $metrics_json); + * } + * + * + * @param IntegrationBase|IntegrationByClassBase $integration The integration instance + * + * @return string JSON-encoded metrics. Returns '{}' if encoding fails. + * + * @see getDTO() + * @see releaseAllSpans() + */ + public static function finalizeDTO($integration) + { + $out = false; + $dto = $integration->getImetricDTO(); + if ($dto && !$dto->is_released) { + $dto->peak_memory_diff_kb = self::getPeakMemoryUsageKb() - $dto->peak_memory_on_start_kb; + $dto->total_exec_time_ms = self::getCurrentTimeMS() - $dto->timer_on_start_msec; + self::releaseAllSpans($dto); + $dto->is_released = true; + $out = $dto->getJSON(); + } + if (!$out) { + $out = new IMetricDTO(); + $out = $out->getJSON(); + if (!$out) { + $out = '{}'; + } + } + return $out; + } + + /** + * Adds a custom field to the DTO's custom_fields array. + * + * Custom fields allow integrations to attach arbitrary performance data. + * Examples: form field count, validation result, user ID, etc. + * + * Safely handles null DTO and released DTO (silently ignores). + * + * Usage: + * + * IMetricService::setCustomField($dto, 'form_fields_count', 15); + * IMetricService::setCustomField($dto, 'validation_passed', true); + * IMetricService::setCustomField($dto, 'processing_stage', 'pre_submission'); + * // Now $dto->custom_fields contains all three fields + * + * + * @param IMetricDTO|null $dto The DTO to update (if null, method is no-op) + * @param string $field_name Custom field key name + * @param mixed $field_value Custom field value (string, number, boolean, array, etc.) + * + * @return void + */ + public static function setCustomField($dto = null, $field_name = 'field', $field_value = null) + { + $dto && !$dto->is_released && $dto->custom_fields[$field_name] = $field_value; + } + + /** + * Tracks the peak memory usage of specific variables. + * + * Serializes each variable and records the maximum serialized size in KB. + * Useful for profiling large data structures being processed by integrations. + * + * Silently skips: + * - Non-serializable objects (unserializable values are caught and skipped) + * - Empty variable arrays + * - Integrations without a DTO + * + * Usage: + * + * $form_data = ['field1' => 'value', 'nested' => ['x' => 'y', ...]]; + * $user_data = get_user_meta($user_id); + * + * IMetricService::dumpVarsSize( + * $integration, + * ['form' => $form_data, 'user' => $user_data], + * 'user_form_data_size' + * ); + * // Now $dto->variable_peak_kb['user_form_data_size'] = largest serialized size + * + * + * The stored value represents the maximum size of any single variable serialized, + * not the sum of all variables. This helps identify which data structure is largest. + * + * @param IntegrationBase|IntegrationByClassBase $integration The integration instance + * @param array $vars Key-value pairs where values are variables to profile + * @param string $span Name for grouping related variable measurements + * + * @return void + */ + public static function dumpVarsSize($integration, array $vars = [], string $span = 'undefined_variable_span') + { + $dto = $integration->getIMetricDTO(); + if (!$dto || $dto->is_released || empty($vars)) { + return; + } + $max_var_size_kb = 0; + foreach ($vars as $_name => $value) { + try { + $size = strlen(serialize($value)); + $current_size = round($size / 1024, 1); + if ($current_size > $max_var_size_kb) { + $max_var_size_kb = $current_size; + } + } catch (\Throwable $e) { + // is unserializable, skip + } + } + $dto->variable_peak_kb[$span] = $max_var_size_kb; + } +} diff --git a/lib/Cleantalk/Antispam/Integrations.php b/lib/Cleantalk/Antispam/Integrations.php index 115e5c04f..34836c68d 100644 --- a/lib/Cleantalk/Antispam/Integrations.php +++ b/lib/Cleantalk/Antispam/Integrations.php @@ -2,7 +2,10 @@ namespace Cleantalk\Antispam; +use Cleantalk\Antispam\IntegrationMetrics\IMetricDTO; +use Cleantalk\Antispam\Integrations\IntegrationBase; use Cleantalk\ApbctWP\Variables\Server; +use Cleantalk\Antispam\IntegrationMetrics\IMetricService; class Integrations { @@ -93,7 +96,7 @@ public function checkSpam($argument, $set_current_integration = '') $class = '\\Cleantalk\\Antispam\\Integrations\\' . $current_integration; if ( class_exists($class) ) { $integration = new $class(); - if ( ! ($integration instanceof \Cleantalk\Antispam\Integrations\IntegrationBase) ) { + if ( ! ($integration instanceof IntegrationBase) ) { // @ToDo have to handle an error do_action( 'apbct_skipped_request', @@ -104,10 +107,16 @@ public function checkSpam($argument, $set_current_integration = '') return true; } + $imetric_dto = IMetricService::getDTO($integration); + if ($imetric_dto) { + $integration->setIMetricDTO($imetric_dto); + } + /** * Run prepare actions. */ $prepare_actions_result = $integration->doPrepareActions($argument); + if ( !is_bool($prepare_actions_result) ) { //if integration returns not a bool value on this state - exit and return modified argument return $prepare_actions_result; @@ -122,10 +131,14 @@ public function checkSpam($argument, $set_current_integration = '') * Data collection */ // If integration provided it's own method - run this + IMetricService::seek($integration, 'collectBaseCallData'); $integration_base_call_data = $integration->collectBaseCallData(); + IMetricService::lease($integration, 'collectBaseCallData'); // old way legacy + IMetricService::seek($integration, 'getDataForChecking'); $data = $integration->getDataForChecking($argument); + IMetricService::lease($integration, 'getDataForChecking'); if ( ! is_null($data) ) { /** @@ -151,6 +164,9 @@ public function checkSpam($argument, $set_current_integration = '') if ( ! empty($integration_fvd['visible_fields']) ) { $sender_info['apbct_visible_fields'] = $integration_fvd['visible_fields']; } + if ( $integration->getIMetricDTO() ) { + $sender_info[IMetricDTO::$SENDER_INFO_KEY] = IMetricService::finalizeDTO($integration); + } // common case $base_call_data = array( 'message' => ! empty($data['message']) ? json_encode($data['message']) : '', diff --git a/lib/Cleantalk/Antispam/Integrations/AmemberRegister.php b/lib/Cleantalk/Antispam/Integrations/AmemberRegister.php index bb1ded204..18c442044 100644 --- a/lib/Cleantalk/Antispam/Integrations/AmemberRegister.php +++ b/lib/Cleantalk/Antispam/Integrations/AmemberRegister.php @@ -14,16 +14,16 @@ public function getDataForChecking($argument) $form_data = array(); $form_data['email'] = isset($_POST['email']) && is_string($_POST['email']) - ? trim($_POST['email']) + ? trim($_POST['email'], " \n\r\t\v\x00") : ''; $form_data['username'] = isset($_POST['login']) && is_string($_POST['login']) - ? trim($_POST['login']) + ? trim($_POST['login'], " \n\r\t\v\x00") : ''; if ( ! empty($_POST['name_f']) && is_string($_POST['name_f']) ) { - $form_data['first_name'] = trim($_POST['name_f']); + $form_data['first_name'] = trim($_POST['name_f'], " \n\r\t\v\x00"); } if ( ! empty($_POST['name_l']) && is_string($_POST['name_l']) ) { - $form_data['last_name'] = trim($_POST['name_l']); + $form_data['last_name'] = trim($_POST['name_l'], " \n\r\t\v\x00"); } /** diff --git a/lib/Cleantalk/Antispam/Integrations/BookingCalendar.php b/lib/Cleantalk/Antispam/Integrations/BookingCalendar.php index 0e36ea65c..a8dd23b2c 100644 --- a/lib/Cleantalk/Antispam/Integrations/BookingCalendar.php +++ b/lib/Cleantalk/Antispam/Integrations/BookingCalendar.php @@ -132,7 +132,7 @@ private function extractFieldByPattern(array $parsed_formdata, $pattern, $expect { foreach ($parsed_formdata as $key => $field) { if (preg_match($pattern, $key)) { - $value = isset($field['value']) ? trim($field['value']) : ''; + $value = isset($field['value']) ? trim($field['value'], " \n\r\t\v\x00") : ''; $type = isset($field['type']) ? $field['type'] : ''; // If type filter specified, check it diff --git a/lib/Cleantalk/Antispam/Integrations/ClassifiedListingRegister.php b/lib/Cleantalk/Antispam/Integrations/ClassifiedListingRegister.php index 5ea9983e5..4554205e9 100644 --- a/lib/Cleantalk/Antispam/Integrations/ClassifiedListingRegister.php +++ b/lib/Cleantalk/Antispam/Integrations/ClassifiedListingRegister.php @@ -17,7 +17,7 @@ public function getDataForChecking($argument) return null; } - $form_data['username'] = isset($_POST['username']) && is_string($_POST['username']) ? trim($_POST['username']) : ''; + $form_data['username'] = isset($_POST['username']) && is_string($_POST['username']) ? trim($_POST['username'], " \n\r\t\v\x00") : ''; $form_data['email'] = isset($_POST['email']) ? $_POST['email'] : ''; if ( ! empty($_POST['first_name']) ) { $form_data['first_name'] = $_POST['first_name']; diff --git a/lib/Cleantalk/Antispam/Integrations/CleantalkPreprocessComment.php b/lib/Cleantalk/Antispam/Integrations/CleantalkPreprocessComment.php index 6fcfba0df..a1d94cf69 100644 --- a/lib/Cleantalk/Antispam/Integrations/CleantalkPreprocessComment.php +++ b/lib/Cleantalk/Antispam/Integrations/CleantalkPreprocessComment.php @@ -483,8 +483,7 @@ private function doSkipReason($current_user, $ct_comment_done) apbct_is_user_enable() === false || $this->apbct->settings['forms__comments_test'] == 0 || $ct_comment_done || - (isset($_SERVER['HTTP_REFERER']) && stripos($_SERVER['HTTP_REFERER'], 'page=wysija_campaigns&action=editTemplate') !== false) || - (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '/wp-admin/') !== false) + is_admin() ) { return __FILE__ . ' -> ' . __FUNCTION__ . '():' . __LINE__; } diff --git a/lib/Cleantalk/Antispam/Integrations/CleantalkWpDieOnComment.php b/lib/Cleantalk/Antispam/Integrations/CleantalkWpDieOnComment.php index 331fa0f5a..c3b93fce4 100644 --- a/lib/Cleantalk/Antispam/Integrations/CleantalkWpDieOnComment.php +++ b/lib/Cleantalk/Antispam/Integrations/CleantalkWpDieOnComment.php @@ -69,9 +69,9 @@ public function doPrepareActions($argument) // first call in the flow - collect data for further instance calling $comment_data = wp_unslash($_POST); $comment_content = TT::getArrayValueAsString($comment_data, 'comment'); - $comment_author = trim(strip_tags(TT::getArrayValueAsString($comment_data, 'author'))); - $comment_author_email = trim(TT::getArrayValueAsString($comment_data, 'email')); - $comment_author_url = trim(TT::getArrayValueAsString($comment_data, 'url')); + $comment_author = trim(strip_tags(TT::getArrayValueAsString($comment_data, 'author')), " \n\r\t\v\x00"); + $comment_author_email = trim(TT::getArrayValueAsString($comment_data, 'email'), " \n\r\t\v\x00"); + $comment_author_url = trim(TT::getArrayValueAsString($comment_data, 'url'), " \n\r\t\v\x00"); $user = function_exists('apbct_wp_get_current_user') ? apbct_wp_get_current_user() : null; diff --git a/lib/Cleantalk/Antispam/Integrations/ElementorPro.php b/lib/Cleantalk/Antispam/Integrations/ElementorPro.php index 0a7c37889..2207d112e 100644 --- a/lib/Cleantalk/Antispam/Integrations/ElementorPro.php +++ b/lib/Cleantalk/Antispam/Integrations/ElementorPro.php @@ -58,7 +58,7 @@ public function getDataForChecking($argument) foreach ( $matches as $match ) { $sender_nickname .= isset($match[0]) && isset($form_data[$match[0]]) ? $form_data[$match[0]] . ' ' : ''; } - $sender_nickname = trim($sender_nickname); + $sender_nickname = trim($sender_nickname, " \n\r\t\v\x00"); } } } diff --git a/lib/Cleantalk/Antispam/Integrations/ElfsightForm.php b/lib/Cleantalk/Antispam/Integrations/ElfsightForm.php index df38b40b4..35e586bd6 100644 --- a/lib/Cleantalk/Antispam/Integrations/ElfsightForm.php +++ b/lib/Cleantalk/Antispam/Integrations/ElfsightForm.php @@ -35,8 +35,8 @@ public function getDataForChecking($argument) if (!is_object($field) || !isset($field->name)) { continue; } - $value = isset($field->value) ? (is_string($field->value) ? trim($field->value) : $field->value) : ''; - $name = mb_strtolower(trim($field->name)); + $value = isset($field->value) ? (is_string($field->value) ? trim($field->value, " \n\r\t\v\x00") : $field->value) : ''; + $name = mb_strtolower(trim($field->name, " \n\r\t\v\x00")); if (strpos($name, 'first') !== false && strpos($name, 'name') !== false) { $result['nickname'] = $value; diff --git a/lib/Cleantalk/Antispam/Integrations/Forminator.php b/lib/Cleantalk/Antispam/Integrations/Forminator.php index 09e637e11..7df9ca4d2 100644 --- a/lib/Cleantalk/Antispam/Integrations/Forminator.php +++ b/lib/Cleantalk/Antispam/Integrations/Forminator.php @@ -19,7 +19,7 @@ public function getDataForChecking($argument) } // First non-empty email-* — empty email-2/3 from hidden multi-step pages must not win. if (is_string($key) && strpos($key, 'email-') === 0) { - $candidate = trim(str_replace(' ', '', TT::toString($value))); + $candidate = trim(str_replace(' ', '', TT::toString($value)), " \n\r\t\v\x00"); if ($candidate !== '' && $email === '') { $email = $candidate; } @@ -38,7 +38,7 @@ public function getDataForChecking($argument) is_array($tmp_data['emails_array']) ) { foreach ($tmp_data['emails_array'] as $emails_array_value) { - $candidate = trim(str_replace(' ', '', TT::toString($emails_array_value))); + $candidate = trim(str_replace(' ', '', TT::toString($emails_array_value)), " \n\r\t\v\x00"); if ($candidate !== '') { $email = $candidate; break; diff --git a/lib/Cleantalk/Antispam/Integrations/IntegrationBase.php b/lib/Cleantalk/Antispam/Integrations/IntegrationBase.php index 2428d6387..5bb782c4f 100644 --- a/lib/Cleantalk/Antispam/Integrations/IntegrationBase.php +++ b/lib/Cleantalk/Antispam/Integrations/IntegrationBase.php @@ -2,8 +2,12 @@ namespace Cleantalk\Antispam\Integrations; +use Cleantalk\Antispam\IntegrationMetrics\IMetricDTOTrait; + abstract class IntegrationBase { + use IMetricDTOTrait; + public $base_call_result; public $visible_fields_data; diff --git a/lib/Cleantalk/Antispam/Integrations/NinjaForms.php b/lib/Cleantalk/Antispam/Integrations/NinjaForms.php index 8d0acba4c..5c0fc0d4d 100644 --- a/lib/Cleantalk/Antispam/Integrations/NinjaForms.php +++ b/lib/Cleantalk/Antispam/Integrations/NinjaForms.php @@ -2,6 +2,7 @@ namespace Cleantalk\Antispam\Integrations; +use Cleantalk\Antispam\IntegrationMetrics\IMetricService; use Cleantalk\ApbctWP\DTO\GetFieldsAnyDTO; use Cleantalk\ApbctWP\Escape; use Cleantalk\ApbctWP\GetFieldsAny; @@ -13,6 +14,14 @@ class NinjaForms extends IntegrationBase { private $sender_email = ''; // needs to provide to final actions + + /** + * @psalm-suppress PossiblyUnusedMethod + */ + public function __construct() + { + $this->imetric_dto_version = '1.0.0'; + } public function getDataForChecking($argument) { global $apbct, $cleantalk_executed; @@ -44,6 +53,7 @@ public function getDataForChecking($argument) $gfa_dto = $this->getGFANew(); } catch (\Exception $_e) { // It is possible here check the reason if the new way collecting fields is not available. + IMetricService::setCustomField($this->imetric_dto, 'nf_old_gfa_used', true); $gfa_dto = $this->getGFAOld(); } @@ -63,6 +73,7 @@ public function getDataForChecking($argument) $form_data = json_decode(stripslashes(Post::getString('formData')), true); } $form_fields = $form_data['fields'] ?? array(); + IMetricService::setCustomField($this->imetric_dto, 'nf_fields_count', count($form_fields)); $gfa_dto = $this->updateEmailNicknameFromNFService($gfa_dto, $form_fields); } @@ -82,6 +93,7 @@ public function getDataForChecking($argument) $fields_visibility_data = GetFieldsAny::getVisibleFieldsData($form_data, true); $this->setVisibleFieldsData($fields_visibility_data); + IMetricService::dumpVarsSize($this, get_defined_vars(), __FUNCTION__); return $gfa_dto->getArray(); } @@ -180,6 +192,7 @@ public function doFinalActions($argument) */ public function getGFANew(): GetFieldsAnyDTO { + IMetricService::seek($this, __FUNCTION__); $form_data = json_decode(Post::getString('formData'), true); if ( ! $form_data ) { $form_data = json_decode(stripslashes(TT::toString(Post::get('formData'))), true); @@ -251,7 +264,9 @@ public function getGFANew(): GetFieldsAnyDTO } } - return ct_gfa_dto($fields, $nf_prior_email, $nickname, $nf_emails_array); + $gfa = ct_gfa_dto($fields, $nf_prior_email, $nickname, $nf_emails_array); + IMetricService::lease($this, __FUNCTION__); + return $gfa; } /** @@ -259,6 +274,7 @@ public function getGFANew(): GetFieldsAnyDTO */ public function getGFAOld(): GetFieldsAnyDTO { + IMetricService::seek($this, __FUNCTION__); /** * Filter for POST */ @@ -272,7 +288,9 @@ public function getGFAOld(): GetFieldsAnyDTO : $input_array; // Return the collected fields data - return ct_gfa_dto($input_data); + $gfa = ct_gfa_dto($input_data); + IMetricService::lease($this, __FUNCTION__); + return $gfa; } @@ -293,6 +311,7 @@ public static function hookPreventSubmission($_some, $_form_id): bool */ public function updateEmailNicknameFromNFService(GetFieldsAnyDTO $gfa_dto, array $nf_form_fields): GetFieldsAnyDTO { + IMetricService::seek($this, __FUNCTION__); if ( function_exists('Ninja_Forms') && !empty($nf_form_fields) ) { /** @psalm-suppress UndefinedFunction */ $nf_form_fields_info = Ninja_Forms()->form()->get_fields(); @@ -323,6 +342,7 @@ public function updateEmailNicknameFromNFService(GetFieldsAnyDTO $gfa_dto, array // if email is empty, fill it with data from Ninja Forms, if not empty, keep DTO $gfa_dto->email = empty($gfa_dto->email) ? $email : $gfa_dto->email; } + IMetricService::lease($this, __FUNCTION__); return $gfa_dto; } diff --git a/lib/Cleantalk/Antispam/Integrations/WordpressFileUpload.php b/lib/Cleantalk/Antispam/Integrations/WordpressFileUpload.php index d0a5b253d..5ec9491a1 100644 --- a/lib/Cleantalk/Antispam/Integrations/WordpressFileUpload.php +++ b/lib/Cleantalk/Antispam/Integrations/WordpressFileUpload.php @@ -16,7 +16,7 @@ public function getDataForChecking($argument) $userdata = explode(";", TT::toString(Request::get('userdata'))); $parsed_userdata = []; foreach ($userdata as $_user) { - $parsed_userdata[] = strip_tags(wfu_plugin_decode_string(trim(substr($_user, 1)))); + $parsed_userdata[] = strip_tags(wfu_plugin_decode_string(trim(substr($_user, 1), " \n\r\t\v\x00"))); } $input_array = apply_filters('apbct__filter_post', $parsed_userdata); diff --git a/lib/Cleantalk/Antispam/IntegrationsByClass.php b/lib/Cleantalk/Antispam/IntegrationsByClass.php index af61d353d..dee6b4b3f 100755 --- a/lib/Cleantalk/Antispam/IntegrationsByClass.php +++ b/lib/Cleantalk/Antispam/IntegrationsByClass.php @@ -2,6 +2,7 @@ namespace Cleantalk\Antispam; +use Cleantalk\Antispam\IntegrationMetrics\IMetricService; use Cleantalk\Antispam\IntegrationsByClass\IntegrationByClassBase; class IntegrationsByClass @@ -50,6 +51,11 @@ public function __construct($integrations) */ $integration = new $class(); + $imetric_dto = IMetricService::getDTO($integration); + if ($imetric_dto) { + $integration->setIMetricDTO($imetric_dto); + } + // Public work if ($integration->isSkipIntegration()) { continue; diff --git a/lib/Cleantalk/Antispam/IntegrationsByClass/IntegrationByClassBase.php b/lib/Cleantalk/Antispam/IntegrationsByClass/IntegrationByClassBase.php index 8fc7cc9e5..e0b069389 100755 --- a/lib/Cleantalk/Antispam/IntegrationsByClass/IntegrationByClassBase.php +++ b/lib/Cleantalk/Antispam/IntegrationsByClass/IntegrationByClassBase.php @@ -2,8 +2,12 @@ namespace Cleantalk\Antispam\IntegrationsByClass; +use Cleantalk\Antispam\IntegrationMetrics\IMetricDTOTrait; + abstract class IntegrationByClassBase { + use IMetricDTOTrait; + /** * Do not apply actions on hooks if true; * @return bool diff --git a/lib/Cleantalk/Antispam/IntegrationsByClass/WPForms.php b/lib/Cleantalk/Antispam/IntegrationsByClass/WPForms.php index e54a75957..7f67e6bdc 100644 --- a/lib/Cleantalk/Antispam/IntegrationsByClass/WPForms.php +++ b/lib/Cleantalk/Antispam/IntegrationsByClass/WPForms.php @@ -98,7 +98,7 @@ public function gatherData($entry, $form) // add unique key if key exist if ($field_label) { - $field_label = mb_strtolower(trim($field_label)); + $field_label = mb_strtolower(trim($field_label, " \n\r\t\v\x00")); $field_label = str_replace(' ', '_', $field_label); $field_label = preg_replace('/\W/u', '', $field_label); diff --git a/lib/Cleantalk/Antispam/IntegrationsByClass/WPSearchForm.php b/lib/Cleantalk/Antispam/IntegrationsByClass/WPSearchForm.php index a6c51b426..574d62272 100644 --- a/lib/Cleantalk/Antispam/IntegrationsByClass/WPSearchForm.php +++ b/lib/Cleantalk/Antispam/IntegrationsByClass/WPSearchForm.php @@ -83,7 +83,7 @@ public function apbctFormSearchAddFields($form_html) preg_match('/form.*method="(.*?)"/', $form_html, $matches); $method = empty($matches[1]) ? 'get' - : trim($matches[1]); + : trim($matches[1], " \n\r\t\v\x00"); } $form_method = strtolower($method); $form_sign = sprintf( diff --git a/lib/Cleantalk/Antispam/IntegrationsByClass/Woocommerce.php b/lib/Cleantalk/Antispam/IntegrationsByClass/Woocommerce.php index bafa1e415..ab1892eb0 100644 --- a/lib/Cleantalk/Antispam/IntegrationsByClass/Woocommerce.php +++ b/lib/Cleantalk/Antispam/IntegrationsByClass/Woocommerce.php @@ -4,6 +4,8 @@ use Cleantalk\Antispam\Cleantalk; use Cleantalk\Antispam\CleantalkRequest; +use Cleantalk\Antispam\IntegrationMetrics\IMetricDTO; +use Cleantalk\Antispam\IntegrationMetrics\IMetricService; use Cleantalk\ApbctWP\Sanitize; use Cleantalk\ApbctWP\Variables\Cookie; use Cleantalk\ApbctWP\Variables\Get; @@ -36,6 +38,14 @@ class Woocommerce extends IntegrationByClassBase { private $event_token = null; + /** + * @psalm-suppress PossiblyUnusedMethod + */ + public function __construct() + { + $this->imetric_dto_version = '1.0.0'; + } + /** * @return void * @psalm-suppress PossiblyUnusedMethod @@ -177,6 +187,11 @@ public function checkoutCheck($_data, $errors) { global $apbct, $cleantalk_executed; + IMetricService::seek( + $this, + __FUNCTION__ + ); + if ( count($errors->errors) ) { return; } @@ -214,7 +229,11 @@ public function checkoutCheck($_data, $errors) 'sender_email' => $sender_email, 'sender_nickname' => $sender_nickname, 'post_info' => $post_info, - 'sender_info' => array('sender_url' => null, 'sender_emails_array' => $sender_emails_array) + 'sender_info' => array( + 'sender_url' => null, + 'sender_emails_array' => $sender_emails_array, + IMetricDTO::$SENDER_INFO_KEY => IMetricService::finalizeDTO($this) + ) ); $base_call_result = apbct_base_call($base_call_data); @@ -256,6 +275,11 @@ public function checkoutCheckFromRest($order) return; } + IMetricService::seek( + $this, + __FUNCTION__ + ); + $sender_email = $order->get_billing_email(); $sender_nickname = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(); $message = $order->get_customer_note(); @@ -269,7 +293,7 @@ public function checkoutCheckFromRest($order) 'sender_email' => $sender_email, 'sender_nickname' => $sender_nickname, 'post_info' => $post_info, - 'sender_info' => array('sender_url' => null), + 'sender_info' => array('sender_url' => null, IMetricDTO::$SENDER_INFO_KEY => IMetricService::finalizeDTO($this)), 'event_token' => $this->event_token, ); @@ -398,6 +422,11 @@ public function addToCartUnloggedUser() { global $apbct; + IMetricService::seek( + $this, + __FUNCTION__ + ); + $data = Post::get('data'); if (is_array($data) && isset($data['ct_bot_detector_event_token'])) { $event_token = $data['ct_bot_detector_event_token']; @@ -422,7 +451,7 @@ public function addToCartUnloggedUser() 'message' => $message, 'post_info' => $post_info, 'js_on' => apbct_js_test(Sanitize::cleanTextField(Cookie::get('ct_checkjs')), true), - 'sender_info' => array('sender_url' => null), + 'sender_info' => array('sender_url' => null, IMetricDTO::$SENDER_INFO_KEY => IMetricService::finalizeDTO($this)), 'exception_action' => false, 'event_token' => $event_token, ) @@ -450,6 +479,10 @@ public function storeApiAddToCartData($add_to_cart_data, $request) { global $apbct; + IMetricService::seek( + $this, + __FUNCTION__ + ); if ( ! $apbct->stats['no_cookie_data_taken'] && $request->get_param('ct_no_cookie_hidden_field') ) { apbct_form__get_no_cookie_data( ['ct_no_cookie_hidden_field' => $request->get_param('ct_no_cookie_hidden_field')], @@ -470,12 +503,13 @@ public function storeApiAddToCartData($add_to_cart_data, $request) $post_info = array(); $post_info['comment_type'] = 'order__add_to_cart'; $post_info['post_url'] = Sanitize::cleanUrl(Server::get('HTTP_REFERER')); + $base_call_result = apbct_base_call( array( 'message' => $message, 'post_info' => $post_info, 'js_on' => apbct_js_test(Sanitize::cleanTextField(Cookie::get('ct_checkjs')), true), - 'sender_info' => array('sender_url' => null), + 'sender_info' => array('sender_url' => null, IMetricDTO::$SENDER_INFO_KEY => IMetricService::finalizeDTO($this)), 'exception_action' => false, 'event_token' => $event_token, ) diff --git a/lib/Cleantalk/ApbctWP/AdminBannersModule/AdminBannerTrialAndRenew.php b/lib/Cleantalk/ApbctWP/AdminBannersModule/AdminBannerTrialAndRenew.php index 489b1c4f6..d3ec48b83 100644 --- a/lib/Cleantalk/ApbctWP/AdminBannersModule/AdminBannerTrialAndRenew.php +++ b/lib/Cleantalk/ApbctWP/AdminBannersModule/AdminBannerTrialAndRenew.php @@ -53,14 +53,14 @@ public function __construct() 'renewal_link' => $renewal_link, 'plugin_settings_link' => $settings_link, 'title_main' => __( - 'Please upgrade your license to keep your site secure and protected!', + 'Please upgrade your license to keep your site protected!', 'cleantalk-spam-protect' ), 'title_numbers' => sprintf( - __('Trusted by %s sites | %s attacks blocked | %s brute-force prevented', 'cleantalk-spam-protect'), + __('Trusted by %s sites | %s attacks blocked | %s spam detection accuracy', 'cleantalk-spam-protect'), '1,079,000+', - '10.5M+', - '1.4M+' + '12,450,238,000+', + '99.9982%' ), 'title_upd' => sprintf( __( diff --git a/lib/Cleantalk/ApbctWP/AdminBannersModule/AdminBannerTrialAndRenewFullpage.php b/lib/Cleantalk/ApbctWP/AdminBannersModule/AdminBannerTrialAndRenewFullpage.php index 9b4594397..3397cbfdf 100644 --- a/lib/Cleantalk/ApbctWP/AdminBannersModule/AdminBannerTrialAndRenewFullpage.php +++ b/lib/Cleantalk/ApbctWP/AdminBannersModule/AdminBannerTrialAndRenewFullpage.php @@ -48,8 +48,8 @@ public function __construct() ? __('Upgrade Your License to Keep Your Site Secure', 'cleantalk-spam-protect') : __('Renew Your License to Keep Your Site Secure', 'cleantalk-spam-protect'), 'subtitle' => $apbct->notice_trial == 1 - ? __('Trial period is now over, please upgrade to premium version to keep your site secure and safe!', 'cleantalk-spam-protect') - : __('Your license has expired, please renew it to keep your site secure and safe!', 'cleantalk-spam-protect'), + ? __('Trial period is now over, please upgrade to premium version to keep your site protected and safe!', 'cleantalk-spam-protect') + : __('Your license has expired, please renew it to keep your site protected and safe!', 'cleantalk-spam-protect'), 'network_statistics_title' => ( __('Our Protection Network Statistics:', 'cleantalk-spam-protect') ), diff --git a/lib/Cleantalk/ApbctWP/BotDetectorService.php b/lib/Cleantalk/ApbctWP/BotDetectorService.php new file mode 100644 index 000000000..a8bc2ccca --- /dev/null +++ b/lib/Cleantalk/ApbctWP/BotDetectorService.php @@ -0,0 +1,285 @@ + [], + 'botd_logic_loaded' => 0, + 'botd_wrapper_loaded' => 0, + ); + + public static function getWrapperUrl(): string + { + return 'https://fd.cleantalk.org/ct-bot-detector-wrapper.js'; + } + + /** + * @return bool + */ + public static function isEnabled() + { + global $apbct; + + // Constant is preferred + if ( Constant::is(Constant::APBCT_SERVICE__BOT_DETECTOR_ENABLED) ) { + return (bool) Constant::getValue(Constant::APBCT_SERVICE__BOT_DETECTOR_ENABLED); + } + // Check by $apbct->data + if ( isset($apbct->data['bot_detector_enabled']) ) { + return (bool) $apbct->data['bot_detector_enabled']; + } + // By default - enabled + return true; + } + + /** + * @return array + */ + public static function getCustomExclusionsFromStateSettings() + { + global $apbct; + + $exlusion_format = array( + 'exclusion_id' => '', + 'signs_to_check' => array( + 'form_attributes' => '', + 'form_children_attributes' => '', + 'form_parent_attributes' => '' + ) + ); + + $exclusions = array(); + if (!$apbct->settings['exclusions__bot_detector']) { + return $exclusions; + } + + foreach ($exlusion_format['signs_to_check'] as $sign => $_val) { + $setting_name = 'exclusions__bot_detector__' . $sign; + if (!empty($apbct->settings[$setting_name])) { + $regexps = explode(',', $apbct->settings[$setting_name]); + for ( $i = 0; $i < count($regexps); $i++ ) { + $form_exclusion = $exlusion_format; + $form_exclusion['exclusion_id'] = 'exclusion_' . $i; + $form_exclusion['signs_to_check'][$sign] = $regexps[$i]; + $exclusions[] = $form_exclusion; + } + } + } + return $exclusions; + } + + /** + * Prepare exclusions for skippping bot-detector event token field. + * @return string JSON encoded array of valid exclusions. If no valid exclusions, returns '{}'. + */ + public static function getPreparedExclusions() + { + global $apbct; + $bot_detector_exclusions = array(); + + //start exclusion there + + //todo if do need to add a built-ib exclusion, use $exlusion_format + //set regexp to chek within attributes + // $exlusion_format = array( + // 'exclusion_id' => '', + // 'signs_to_check' => array( + // 'form_attributes' => '', + // 'form_children_attributes' => '', + // 'form_parent_attributes' => '' + // ) + // ); + if ($apbct->settings['exclusions__bot_detector']) { + $bot_detector_exclusions = array_merge( + $bot_detector_exclusions, + self::getCustomExclusionsFromStateSettings() + ); + } + + //start validate + $bot_detector_exclusions_valid = array(); + foreach ($bot_detector_exclusions as $exclusion) { + if ( + empty($exclusion['exclusion_id']) || + ( + empty($exclusion['signs_to_check']['form_attributes']) && + empty($exclusion['signs_to_check']['form_children_attributes']) && + empty($exclusion['signs_to_check']['form_parent_attributes']) + ) + ) { + continue; + } + $bot_detector_exclusions_valid[] = $exclusion; + } + + //prepare for early localize + $bot_detector_exclusions_valid = json_encode($bot_detector_exclusions_valid); + return $bot_detector_exclusions_valid !== false ? $bot_detector_exclusions_valid : '{}'; + } + + /** + * Get the list of fired bot detector exclusions from the cookie. + * + * @return string The value of the 'ct_bot_detector_form_exclusion' cookie, or an empty string if the cookie is not set. + */ + public static function getFiredExclusions() + { + return Cookie::getString('ct_bot_detector_form_exclusion'); + } + + /** + * Check if the current request should skip the bot detector flow, e.g. Oxygen builder requests. + * + * @return bool True if the request is a NoScript flow, false otherwise. + */ + public static function isNoScripFlow() + { + if (apbct_is_plugin_active('oxygen/functions.php') && Get::getBool('ct_builder')) { + return true; + } + + return false; + } + + /** + * Return bot detector frontend data log from Alt Sessions if data found. + * Format: JSON. + * + * @return string JSON encoded bot detector frontend data log. + */ + public static function getFrontendDataLog() + { + $result = array( + 'plugin_status' => 'OK', + 'error_msg' => '', + 'apbct_browser_state' => self::$default_browser_state, + ); + + try { + if (Constant::is(Constant::APBCT_SERVICE__DO_NOT_COLLECT_FRONTEND_DATA_LOGS)) { + $result['plugin_status'] = 'OK'; + $result['error_msg'] = 'bot detector logs collection is disabled via constant definition'; + } + + if ( ! self::isEnabled() ) { + throw new \Exception('bot detector library usage is disabled'); + } + + $sources = array( + 'request_parameters' => RequestParameters::get('apbct_browser_state'), // NoCookie hidden field or alternative sessions are both covered by RequestParameters + 'post_browser_state' => Post::getString('apbct_browser_state'), // XHR interception transport - look at the POST directly + 'post_data' => Post::getArray('data'), //XHR interception transport - the state could be wrapped to the data[] array + ); + + $browser_state = self::getBrowserState($sources); + + if ( empty($browser_state) ) { + throw new \Exception('no browser state provided by the transport'); + } + + $result['apbct_browser_state'] = $browser_state; + } catch (\Exception $e) { + $result['plugin_status'] = 'ERROR'; + $result['error_msg'] = $e->getMessage(); + } + + // Return the result as a JSON encoded string + $json = json_encode($result); + if ($json === false) { + $json = json_encode(array( + 'plugin_status' => 'ERROR', + 'error_msg' => 'json_encode failed: ' . json_last_error_msg(), + 'apbct_browser_state' => self::$default_browser_state, + )); + } + return $json !== false ? $json : '{"plugin_status":"ERROR","error_msg":"json_encode failed","apbct_browser_state":{}}'; + } + + /** + * Get the browser state gathered by the plugin JS. + * + * The state comes with the transport the site is currently configured to use: + * NoCookie hidden field or alternative sessions are both covered by RequestParameters, + * the XHR interception passes the state as a plain POST field. + * Native cookies do not store the state in cookies (cookie size limits) + * + * @return array Empty array if no state provided. + */ + public static function getBrowserState(array $sources = array()) + { + $raw_state = null; + $log_source = 'unknown'; + + if (!empty($sources['request_parameters'])) { + $raw_state = $sources['request_parameters']; + $log_source = 'request_parameters'; + } + + // XHR interception transport - look at the POST directly + if ( empty($raw_state) ) { + $raw_state = $sources['post_browser_state'] ?? null; + if ($raw_state) { + $log_source = 'post_browser_state'; + } + } + + // XHR interception transport - the state could be wrapped to the data[] array + if ( empty($raw_state) ) { + $post_data = $sources['post_data'] ?? null; + if ( is_array($post_data) && ! empty($post_data['apbct_browser_state']) ) { + $raw_state = $post_data['apbct_browser_state']; + $log_source = 'post_data'; + } + } + + if ( empty($raw_state) ) { + return array(); + } + + $state = null; + + // request param can be string or array, depending on the transport used. + // The XHR interception transport passes the state as a plain POST field, which is a string. + if (is_string($raw_state)) { + $state = @json_decode($raw_state, true); + + if (null === $state) { + $raw_state = stripslashes($raw_state); + $state = @json_decode($raw_state, true); + } + } elseif (is_array($raw_state)) { + $state = $raw_state; + } + + if ( ! $state ) { + return array(); + } + + // log is mixed indeed, try to convert to array, if not - return empty array + $fd_log = array(); + if (isset($state['frontend_data_log'])) { + if (is_array($state['frontend_data_log'])) { + $fd_log = $state['frontend_data_log']; + } elseif (is_string($state['frontend_data_log'])) { + $fd_log = @json_decode($state['frontend_data_log'], true); + $fd_log = is_array($fd_log) ? $fd_log : array(); + } + } + + return array( + 'frontend_data_log' => $fd_log, + 'log_source' => $log_source, + 'botd_logic_loaded' => TT::getArrayValueAsInt($state, 'botd_logic_loaded'), + 'botd_wrapper_loaded' => TT::getArrayValueAsInt($state, 'botd_wrapper_loaded'), + 'transport_enabled' => TT::getArrayValueAsInt($state, 'transport_enabled'), + ); + } +} diff --git a/lib/Cleantalk/ApbctWP/Constant.php b/lib/Cleantalk/ApbctWP/Constant.php index e4775dd0b..6fb93df9f 100644 --- a/lib/Cleantalk/ApbctWP/Constant.php +++ b/lib/Cleantalk/ApbctWP/Constant.php @@ -170,6 +170,10 @@ class Constant */ const CLEANTALK_SERVER = 'APBCT_SERVICE__PREDEFINED_CLEANTALK_SERVER_URL'; + /** + * If defined, integration metrics will be disabled. + */ + const APBCT_SERVICE__DISABLE_INTEGRATION_METRICS = 'APBCT_SERVICE__DISABLE_INTEGRATION_METRICS'; /** * Registry cache. Built once per request by self::getRegistry(). * @@ -465,6 +469,13 @@ private static function getRegistry() 'type' => 'string', 'description' => 'Provides own URL of API server.', ), + self::APBCT_SERVICE__DISABLE_INTEGRATION_METRICS => array( + 'names' => array( + self::APBCT_SERVICE__DISABLE_INTEGRATION_METRICS, + ), + 'type' => 'bool', + 'description' => 'If defined, integration metrics will be disabled.', + ), ); } diff --git a/lib/Cleantalk/ApbctWP/ContactsEncoder/ContactsEncoder.php b/lib/Cleantalk/ApbctWP/ContactsEncoder/ContactsEncoder.php index 3184b2ace..3cceeda4a 100644 --- a/lib/Cleantalk/ApbctWP/ContactsEncoder/ContactsEncoder.php +++ b/lib/Cleantalk/ApbctWP/ContactsEncoder/ContactsEncoder.php @@ -41,11 +41,6 @@ class ContactsEncoder extends \Cleantalk\Common\ContactsEncoder\ContactsEncoder */ private $grid_builder_integration; - /** - * @var string[] - */ - public $decoded_contacts_array = array(); - /** * @var null|string Comment from API response */ @@ -154,7 +149,7 @@ public function runEncoding($content = '') */ public function modifyFormFieldDisplay($html, $field, $display_context, $post_id) { - if (mb_strpos($html, 'mailto:') !== false) { + if (mb_stripos($html, 'mailto:') !== false) { $html = html_entity_decode($html); return $this->modifyContent($html); } @@ -475,6 +470,36 @@ public static function getEmailsEncodingDescription() return __('Encode email addresses', 'cleantalk-spam-protect'); } + public static function getExcludedStringsDescription() + { + return __( + 'List emails, phone numbers or text fragments that must never be encoded. Put one value per line. Each value is limited to 128 characters, up to 20 values.', + 'cleantalk-spam-protect' + ); + } + + public static function getExcludedStringsLongDescription() + { + $tmp = ' +

%s

+

%s

+

%s

+

%s

+

%s

+

%s

+ '; + $tmp = sprintf( + $tmp, + __('Use this list when you need a contact to stay readable everywhere, including titles, menus and widgets — WordPress does not run shortcodes in those places.', 'cleantalk-spam-protect'), + __('Put one value per line:', 'cleantalk-spam-protect'), + __('an email, e.g. support@example.com', 'cleantalk-spam-protect'), + __('a phone number, e.g. +1 (234) 567-8901 — format differences are ignored', 'cleantalk-spam-protect'), + __('a text fragment, e.g. example.com to skip all emails on that domain', 'cleantalk-spam-protect'), + __('Each value is sliced to 128 characters. The list is limited to 20 values.', 'cleantalk-spam-protect') + ); + return $tmp; + } + public static function getPhonesEncodingLongDescription() { $tmp = ' @@ -496,7 +521,7 @@ public static function getPhonesEncodingLongDescription()

%s

'; $tmp = sprintf( - trim($tmp), + trim($tmp, " \n\r\t\v\x00"), __('Enable this option to encode contact phone numbers', 'cleantalk-spam-protect'), __('There are a few requirements to the number format:', 'cleantalk-spam-protect'), __('Should starting with "+" symbol or opening brace', 'cleantalk-spam-protect'), diff --git a/lib/Cleantalk/ApbctWP/ContactsEncoder/Integrations/CEIntegrationCommentList.php b/lib/Cleantalk/ApbctWP/ContactsEncoder/Integrations/CEIntegrationCommentList.php deleted file mode 100644 index 9b7d12942..000000000 --- a/lib/Cleantalk/ApbctWP/ContactsEncoder/Integrations/CEIntegrationCommentList.php +++ /dev/null @@ -1,187 +0,0 @@ - - */ - private $region_placeholders = array(); - - /** - * @param string $content - * - * @return string - */ - public function protect($content) - { - if ( ! is_string($content) || $content === '' ) { - return $content; - } - - if ( - stripos($content, 'comment-list') === false - && stripos($content, 'id="comments"') === false - && stripos($content, "id='comments'") === false - ) { - return $content; - } - - $this->region_placeholders = array(); - - $content = $this->protectElementsById($content, 'comments'); - $content = $this->protectElementsByClass($content, 'comment-list', 'ol'); - $content = $this->protectElementsByClass($content, 'comment-list', 'ul'); - - return $content; - } - - /** - * @param string $content - * - * @return string - */ - public function restore($content) - { - if ( ! is_string($content) || $this->region_placeholders === array() ) { - return $content; - } - - $content = strtr($content, $this->region_placeholders); - $this->region_placeholders = array(); - - return $content; - } - - /** - * @param string $content - * @param string $id - * - * @return string - */ - private function protectElementsById($content, $id) - { - $pattern = '/]*\bid=(["\'])' . preg_quote($id, '/') . '\1)/i'; - - return $this->protectByOpeningTagPattern($content, $pattern, 'div'); - } - - /** - * @param string $content - * @param string $class - * @param string $tag_name - * - * @return string - */ - private function protectElementsByClass($content, $class, $tag_name) - { - $pattern = '/<' . $tag_name . '\b(?=[^>]*\bclass=(["\'])[^"\']*\b' - . preg_quote($class, '/') - . '\b[^"\']*\1)/i'; - - return $this->protectByOpeningTagPattern($content, $pattern, $tag_name); - } - - /** - * @param string $content - * @param string $open_pattern - * @param string $tag_name - * - * @return string - */ - private function protectByOpeningTagPattern($content, $open_pattern, $tag_name) - { - $offset = 0; - - while ( preg_match($open_pattern, $content, $matches, PREG_OFFSET_CAPTURE, $offset) ) { - $start = $matches[0][1] ?? null; - - if ( $start === null ) { - break; - } - - $element = $this->extractBalancedElement($content, $start, $tag_name); - - if ( $element === null ) { - $offset = $start + 1; - continue; - } - - $placeholder = '%%APBCT_COMMENT_REGION_' . count($this->region_placeholders) . '%%'; - $this->region_placeholders[$placeholder] = $element; - - $content = substr($content, 0, $start) . $placeholder . substr($content, $start + strlen($element)); - $offset = $start + strlen($placeholder); - } - - return $content; - } - - /** - * @param string $content - * @param int $start - * @param string $tag_name - * - * @return string|null - */ - private function extractBalancedElement($content, $start, $tag_name) - { - $open_end = strpos($content, '>', $start); - - if ( $open_end === false ) { - return null; - } - - $depth = 1; - $pos = $open_end + 1; - $length = strlen($content); - $open_needle = '<' . $tag_name; - $close_needle = ' 0 ) { - $next_open = stripos($content, $open_needle, $pos); - $next_close = stripos($content, $close_needle, $pos); - - if ( $next_close === false ) { - return null; - } - - if ( $next_open !== false && $next_open < $next_close && $this->isTagOpenAt($content, $next_open, $tag_name) ) { - $depth++; - $pos = $next_open + 1; - continue; - } - - $depth--; - $close_end = strpos($content, '>', $next_close); - - if ( $close_end === false ) { - return null; - } - - $pos = $close_end + 1; - - if ( $depth === 0 ) { - return substr($content, $start, $pos - $start); - } - } - - return null; - } - - /** - * @param string $content - * @param int $offset - * @param string $tag_name - * - * @return bool - */ - private function isTagOpenAt($content, $offset, $tag_name) - { - return (bool) preg_match('/^<' . preg_quote($tag_name, '/') . '\b/i', substr($content, $offset, strlen($tag_name) + 2)); - } -} diff --git a/lib/Cleantalk/ApbctWP/ContactsEncoder/Integrations/CEIntegrationGridBuilder.php b/lib/Cleantalk/ApbctWP/ContactsEncoder/Integrations/CEIntegrationGridBuilder.php index 1133f1edc..d803fb9b0 100644 --- a/lib/Cleantalk/ApbctWP/ContactsEncoder/Integrations/CEIntegrationGridBuilder.php +++ b/lib/Cleantalk/ApbctWP/ContactsEncoder/Integrations/CEIntegrationGridBuilder.php @@ -421,7 +421,7 @@ private function appendCardCssChunk($css) return; } - $css = trim($css); + $css = trim($css, " \n\r\t\v\x00"); if ( $css === '' ) { return; @@ -454,7 +454,7 @@ private function mergeCardCssChunks($chunks) continue; } - $chunk = trim($chunk); + $chunk = trim($chunk, " \n\r\t\v\x00"); if ( $chunk !== '' ) { $merged[] = $chunk; @@ -463,7 +463,7 @@ private function mergeCardCssChunks($chunks) if ( $merged === array() ) { return $this->isCardCssChunk($this->card_inline_css) - ? trim($this->card_inline_css) + ? trim($this->card_inline_css, " \n\r\t\v\x00") : ''; } @@ -471,7 +471,7 @@ private function mergeCardCssChunks($chunks) $this->card_inline_css !== '' && $this->isCardCssChunk($this->card_inline_css) ) { - $merged[] = trim($this->card_inline_css); + $merged[] = trim($this->card_inline_css, " \n\r\t\v\x00"); } return implode("\n", array_unique($merged)); @@ -626,7 +626,7 @@ private function readCssFromSrc($url) return ''; } - return trim($css); + return trim($css, " \n\r\t\v\x00"); } /** @@ -668,7 +668,7 @@ private function extractCardCssFromHtml($content) continue; } - $css = trim($css); + $css = trim($css, " \n\r\t\v\x00"); if ( $css !== '' ) { $chunks[] = $css; @@ -713,7 +713,7 @@ private function collectInlineCssFromQueue() foreach ( $data as $piece ) { if ( is_string($piece) && $this->isCardCssChunk($piece) ) { - $chunks[] = trim($piece); + $chunks[] = trim($piece, " \n\r\t\v\x00"); } } } diff --git a/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/EmailEncoderShortCode.php b/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/EmailEncoderShortCode.php index 7ff272094..224b525e9 100644 --- a/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/EmailEncoderShortCode.php +++ b/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/EmailEncoderShortCode.php @@ -15,6 +15,66 @@ class EmailEncoderShortCode extends \Cleantalk\ApbctWP\ShortCode */ protected $public_name; + /** + * @var string Wrapper template overridden by child classes as the placeholder source. + */ + protected $exclusion_wrapper = ''; + + // Placeholder nonce for ensuring unique placeholders per render. + protected $placeholder_nonce = ''; + + /** + * Build a placeholder for the given counter using the child's $exclusion_wrapper as a template. + * Lazy-initialises the per-render nonce so replacements survive isolated render passes. + * + * @param int $counter + * + * @return string + */ + protected function buildPlaceholder($counter) + { + if ($this->placeholder_nonce === '') { + $this->placeholder_nonce = $this->generatePlaceholderNonce(); + } + + $wrapper = (string)$this->exclusion_wrapper; + $placeholder = preg_replace( + '/EE\_\d+/', + 'EE_' . (string)$counter . '_' . $this->placeholder_nonce, + $wrapper + ); + + return is_null($placeholder) ? $wrapper : $placeholder; + } + + /** + * Rotates the placeholder nonce to ensure unique placeholders for subsequent renders. + * @return void + */ + protected function rotatePlaceholderNonce() + { + $this->placeholder_nonce = $this->generatePlaceholderNonce(); + } + + /** + * Generates a new high-entropy nonce for placeholders. + * @return string + */ + protected function generatePlaceholderNonce() + { + if (function_exists('random_bytes')) { + try { + return bin2hex(random_bytes(16)); + } catch (\Exception $e) { + // fall through to WP fallback + } + } + if (function_exists('wp_generate_password')) { + return strtolower(wp_generate_password(32, false)); + } + return substr(hash('sha256', uniqid((string)mt_rand(), true)), 0, 32); + } + /** * Process only this encoder's shortcode tags in the content. * @@ -51,6 +111,10 @@ function ($matches) { $inner_content = isset($matches[2]) ? $matches[2] : ''; + if ( $this->shortcodeContentContainsHtmlTags($inner_content) ) { + return isset($matches[0]) ? $matches[0] : ''; + } + return $this->callback($atts, $inner_content, $this->public_name); }, $content @@ -135,6 +199,26 @@ protected function isShortcodeInsideHtmlTag($content) return false; } + /** + * Skip shortcode pairs whose inner content contains HTML tags. + * + * In buffer mode the lazy [tag]...[/tag] match can pair an opener in one + * fragment with a closer in another and swallow everything between them + * (comments, articles, any markup). A legitimate shortcode wraps text only. + * + * @param string $content Inner shortcode content. + * + * @return bool + */ + protected function shortcodeContentContainsHtmlTags($content) + { + if ( ! is_string($content) || $content === '' ) { + return false; + } + + return (bool) preg_match('/<\/?[a-zA-Z][a-zA-Z0-9:-]*(?:\s[^<>]*)?>/', $content); + } + /** * Determines whether a given character offset is located inside an HTML tag. * diff --git a/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/EncodeContentSC.php b/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/EncodeContentSC.php index fb65b16d2..b472b0c46 100644 --- a/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/EncodeContentSC.php +++ b/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/EncodeContentSC.php @@ -115,18 +115,20 @@ public function changeContentBeforeEncoderModify($content) // Extract shortcode content to protect it from email encoding, supports sc attributes(!) $shortcode_exist_pattern = sprintf('/(\[%s(?:\s[^\]]*)?\])([\s\S]*?)(\[\/%s\])/s', $this->public_name, $this->public_name); $content = preg_replace_callback($shortcode_exist_pattern, function ($matches) { - $placeholder = preg_replace('/EE\_\d+/', 'EE_' . (string)$this->shortcode_counter++, $this->exclusion_wrapper); - if (is_null($placeholder)) { - $placeholder = $this->exclusion_wrapper; + if ( ! isset($matches[1], $matches[2], $matches[3]) ) { + return isset($matches[0]) ? $matches[0] : ''; } - if (isset($matches[1], $matches[2], $matches[3])) { - $prefix = $matches[1]; - $entity = $matches[2]; - $suffix = $matches[3]; - $entity = Escape::escKsesPost($entity); - $this->shortcode_replacements[$placeholder] = $prefix . $entity . $suffix; + + if ( $this->shortcodeContentContainsHtmlTags($matches[2]) ) { + return isset($matches[0]) ? $matches[0] : ''; } + $placeholder = $this->buildPlaceholder($this->shortcode_counter++); + $prefix = $matches[1]; + $entity = Escape::escKsesPost($matches[2]); + $suffix = $matches[3]; + $this->shortcode_replacements[$placeholder] = $prefix . $entity . $suffix; + return $placeholder; }, $content); return $content; @@ -166,5 +168,6 @@ public function resetShortcodeReplacements() { $this->shortcode_replacements = array(); $this->shortcode_counter = 0; + $this->rotatePlaceholderNonce(); } } diff --git a/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/ExcludedEncodeContentSC.php b/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/ExcludedEncodeContentSC.php index 01b59208e..526ebf9c0 100644 --- a/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/ExcludedEncodeContentSC.php +++ b/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/ExcludedEncodeContentSC.php @@ -89,7 +89,11 @@ public function changeContentBeforeEncoderModify($content) $pattern = '/\[apbct_skip_encoding\](.*?)\[\/apbct_skip_encoding\]/s'; return preg_replace_callback($pattern, function ($matches) { - if (isset($matches[1])) { + if ( isset($matches[1]) ) { + if ( $this->shortcodeContentContainsHtmlTags($matches[1]) ) { + return isset($matches[0]) ? $matches[0] : ''; + } + return $this->createPlaceholder($matches[1]); } @@ -174,6 +178,10 @@ protected function processSkipEncodingShortcodes($content) return preg_replace_callback($pattern, function ($matches) { if ( isset($matches[1]) ) { + if ( $this->shortcodeContentContainsHtmlTags($matches[1]) ) { + return isset($matches[0]) ? $matches[0] : ''; + } + return $this->callback([], $matches[1], ''); } /** @psalm-suppress PossiblyUndefinedIntArrayOffset */ @@ -275,10 +283,7 @@ protected function shouldDeferPlaceholderRestore() */ protected function createPlaceholder($content) { - $placeholder = preg_replace('/EE\_\d+/', 'EE_' . (string)$this->shortcode_counter++, $this->exclusion_wrapper); - if (is_null($placeholder)) { - $placeholder = $this->exclusion_wrapper; - } + $placeholder = $this->buildPlaceholder($this->shortcode_counter++); $this->shortcode_replacements[$placeholder] = $content; return $placeholder; @@ -291,6 +296,7 @@ public function resetShortcodeReplacements() { $this->shortcode_replacements = array(); $this->shortcode_counter = 0; + $this->rotatePlaceholderNonce(); } /** @@ -591,7 +597,7 @@ protected function removeDuplicateContactsOutsideShortcodes($title) $protected_contacts = array(); foreach ( $matches[1] as $inner_match ) { - $inner = trim($inner_match[0]); + $inner = trim($inner_match[0], " \n\r\t\v\x00"); if ( $inner !== '' ) { $protected_contacts[$inner] = true; } @@ -615,7 +621,7 @@ protected function removeDuplicateContactsOutsideShortcodes($title) $result .= $this->stripProtectedContactsFromPlainText(substr($title, $offset), array_keys($protected_contacts)); - return trim(preg_replace('/\s+/', ' ', $result)); + return trim(preg_replace('/\s+/', ' ', $result), " \n\r\t\v\x00"); } /** @@ -913,7 +919,7 @@ public function processTitleString($title, $strip_html = true) if ( $strip_html ) { $result = wp_strip_all_tags($result); - $result = trim(preg_replace('/\s+/', ' ', $result)); + $result = trim(preg_replace('/\s+/', ' ', $result), " \n\r\t\v\x00"); } return $result; @@ -931,7 +937,7 @@ public static function stripShortcodesForSlug($title) $title = preg_replace('/\[apbct_skip_encoding\](.*?)\[\/apbct_skip_encoding\]/s', '$1', $title); $title = preg_replace('/\[\/?apbct_skip_encoding\]/', '', $title); - return trim(preg_replace('/\s+/', ' ', $title)); + return trim(preg_replace('/\s+/', ' ', $title), " \n\r\t\v\x00"); } /** diff --git a/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/ShortCodesService.php b/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/ShortCodesService.php index 7b716ae2a..7dbdd82c5 100644 --- a/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/ShortCodesService.php +++ b/lib/Cleantalk/ApbctWP/ContactsEncoder/Shortcodes/ShortCodesService.php @@ -2,7 +2,6 @@ namespace Cleantalk\ApbctWP\ContactsEncoder\Shortcodes; -use Cleantalk\ApbctWP\ContactsEncoder\Integrations\CEIntegrationCommentList; use Cleantalk\Common\ContactsEncoder\Dto\Params; /** @@ -16,11 +15,6 @@ class ShortCodesService public $shortcodes_registered = false; - /** - * @var CEIntegrationCommentList - */ - private $comment_list_integration; - /** * @return void */ @@ -71,7 +65,6 @@ public function __construct(Params $params) { $this->encode = new EncodeContentSC($params); $this->shortcode_to_exclude = new ExcludedEncodeContentSC(); - $this->comment_list_integration = new CEIntegrationCommentList(); } public function addActionsBeforeModify($hook, $priority = 1) @@ -107,7 +100,6 @@ public function modifyBufferBefore($buffer) { $this->encode->resetShortcodeReplacements(); $this->shortcode_to_exclude->resetShortcodeReplacements(); - $buffer = $this->comment_list_integration->protect($buffer); $buffer = $this->shortcode_to_exclude->changeContentBeforeEncoderModify($buffer); return $this->encode->changeContentBeforeEncoderModify($buffer); @@ -128,14 +120,11 @@ public function modifyBufferAfter($buffer) if ( $apbct->settings['data__email_decoder_buffer'] ) { $buffer = $this->shortcode_to_exclude->finalizeBufferAfterEncoding($buffer); - $buffer = $this->comment_list_integration->restore($buffer); $apbct->buffer = $buffer; return $buffer; } - $buffer = $this->shortcode_to_exclude->changeContentAfterEncoderModify($buffer); - - return $this->comment_list_integration->restore($buffer); + return $this->shortcode_to_exclude->changeContentAfterEncoderModify($buffer); } } diff --git a/lib/Cleantalk/ApbctWP/Cron.php b/lib/Cleantalk/ApbctWP/Cron.php index 10953ac2a..1ce365021 100644 --- a/lib/Cleantalk/ApbctWP/Cron.php +++ b/lib/Cleantalk/ApbctWP/Cron.php @@ -67,10 +67,10 @@ public function getTasks() } $unserialize_options = array('allowed_classes' => false); - $unserialized = @unserialize(trim($result), $unserialize_options); + $unserialized = @unserialize(trim($result, " \n\r\t\v\x00"), $unserialize_options); if ( is_string($unserialized) && is_serialized($unserialized) ) { - $unserialized = @unserialize(trim($unserialized), $unserialize_options); + $unserialized = @unserialize(trim($unserialized, " \n\r\t\v\x00"), $unserialize_options); } return is_array($unserialized) ? $unserialized : array(); diff --git a/lib/Cleantalk/ApbctWP/FindSpam/CommentsChecker.php b/lib/Cleantalk/ApbctWP/FindSpam/CommentsChecker.php index e8ffefeb7..e01b2c08c 100644 --- a/lib/Cleantalk/ApbctWP/FindSpam/CommentsChecker.php +++ b/lib/Cleantalk/ApbctWP/FindSpam/CommentsChecker.php @@ -162,8 +162,8 @@ private static function removeSkipRoles(array $comments, array $skip_roles) private static function removeCommentsWithoutIPEmail(array $comments) { foreach ($comments as $index => $comment) { - $comment_ip = ! empty($comment->comment_author_IP) ? trim($comment->comment_author_IP) : false; - $comment_email = ! empty($comment->comment_author_email) ? trim($comment->comment_author_email) : false; + $comment_ip = ! empty($comment->comment_author_IP) ? trim($comment->comment_author_IP, " \n\r\t\v\x00") : false; + $comment_email = ! empty($comment->comment_author_email) ? trim($comment->comment_author_email, " \n\r\t\v\x00") : false; // Validate IP and Email $comment_ip = filter_var($comment_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); diff --git a/lib/Cleantalk/ApbctWP/FindSpam/UsersChecker.php b/lib/Cleantalk/ApbctWP/FindSpam/UsersChecker.php index a43635606..7a7124ed4 100644 --- a/lib/Cleantalk/ApbctWP/FindSpam/UsersChecker.php +++ b/lib/Cleantalk/ApbctWP/FindSpam/UsersChecker.php @@ -175,7 +175,7 @@ private static function removeUsersWithoutIPEmail(array $users) ? $ip_from_keeper : false; $user_ip = $ip_from_keeper; - $user_email = ! empty($user->user_email) ? trim($user->user_email) : false; + $user_email = ! empty($user->user_email) ? trim($user->user_email, " \n\r\t\v\x00") : false; // Validate IP and Email $user_ip = filter_var($user_ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); diff --git a/lib/Cleantalk/ApbctWP/Firewall/AntiCrawler.php b/lib/Cleantalk/ApbctWP/Firewall/AntiCrawler.php index 1b4ab0bf8..92a607178 100644 --- a/lib/Cleantalk/ApbctWP/Firewall/AntiCrawler.php +++ b/lib/Cleantalk/ApbctWP/Firewall/AntiCrawler.php @@ -21,7 +21,7 @@ */ class AntiCrawler extends \Cleantalk\Common\Firewall\FirewallModule { - const COOKIE_NAME__ANTIBOT = 'wordpress_apbct_antibot'; + const COOKIE_NAME__ANTIBOT = 'apbct_antibot'; const COOKIE_NAME__ANTICRAWLER_PASSED = 'apbct_anticrawler_passed'; const PARAM_NAME__BOT_DETECTOR_EXIST = 'apbct_bot_detector_exist'; diff --git a/lib/Cleantalk/ApbctWP/Firewall/SFW.php b/lib/Cleantalk/ApbctWP/Firewall/SFW.php index a8d6b0c54..4a13f0121 100644 --- a/lib/Cleantalk/ApbctWP/Firewall/SFW.php +++ b/lib/Cleantalk/ApbctWP/Firewall/SFW.php @@ -606,7 +606,7 @@ public static function sendLog($db, $log_table, $ct_key) $ids_invalid = array(); $data = array(); foreach ($logs as $_key => &$value) { - $ip = isset($value['ip']) ? trim((string)$value['ip']) : ''; + $ip = isset($value['ip']) ? trim((string)$value['ip'], " \n\r\t\v\x00") : ''; // Do not send empty/invalid IPs — they break cloud collectors. if ( Helper::ipValidate($ip) === false ) { diff --git a/lib/Cleantalk/ApbctWP/Firewall/die_page_anticrawler.html b/lib/Cleantalk/ApbctWP/Firewall/die_page_anticrawler.html index 045ef6e86..1051d955a 100644 --- a/lib/Cleantalk/ApbctWP/Firewall/die_page_anticrawler.html +++ b/lib/Cleantalk/ApbctWP/Firewall/die_page_anticrawler.html @@ -234,7 +234,7 @@

{SFW_DIE_NOTICE_IP}

date.setDate(date.getDate() + 30); ctSetCookie( [ - ['wordpress_apbct_antibot', escape('{COOKIE_ANTICRAWLER}'), date.toUTCString()], + ['apbct_antibot', escape('{COOKIE_ANTICRAWLER}'), date.toUTCString()], ['apbct_anticrawler_passed', escape('{COOKIE_ANTICRAWLER_PASSED}'), date.toUTCString()] ] ); diff --git a/lib/Cleantalk/ApbctWP/Firewall/die_page_sfw.html b/lib/Cleantalk/ApbctWP/Firewall/die_page_sfw.html index 034de54be..8d4aedf50 100644 --- a/lib/Cleantalk/ApbctWP/Firewall/die_page_sfw.html +++ b/lib/Cleantalk/ApbctWP/Firewall/die_page_sfw.html @@ -245,7 +245,7 @@

{SFW_DIE_CLICK_TO_PASS}

ctSetCookie( [ ['{COOKIE_PREFIX}ct_sfw_pass_key', escape('{COOKIE_SFW}'), date.toUTCString()], - ['{COOKIE_PREFIX}wordpress_apbct_antibot', escape('{COOKIE_ANTICRAWLER}'), date.toUTCString()], + ['{COOKIE_PREFIX}apbct_antibot', escape('{COOKIE_ANTICRAWLER}'), date.toUTCString()], ['{COOKIE_PREFIX}ct_sfw_passed', '1', date.toUTCString()] ] ); diff --git a/lib/Cleantalk/ApbctWP/GetFieldsAny.php b/lib/Cleantalk/ApbctWP/GetFieldsAny.php index f5855482c..37c0726e6 100644 --- a/lib/Cleantalk/ApbctWP/GetFieldsAny.php +++ b/lib/Cleantalk/ApbctWP/GetFieldsAny.php @@ -255,7 +255,7 @@ public function prepareFields($email, $nickname, $emails_array) foreach ($name_chunks as $value) { $this->dto->nickname .= ($value ? $value . " " : ""); } - $this->dto->nickname = trim($this->dto->nickname); + $this->dto->nickname = trim($this->dto->nickname, " \n\r\t\v\x00"); } } @@ -358,9 +358,9 @@ private function processRecursive($arr) } // Removes shortcodes to do better spam filtration on server side. - $value_for_email = trim($this->stripShortcodes($value)); + $value_for_email = trim($this->stripShortcodes($value), " \n\r\t\v\x00"); // Removes whitespaces - $value = urldecode(trim($this->stripShortcodes($value))); // Fully cleaned message + $value = urldecode(trim($this->stripShortcodes($value), " \n\r\t\v\x00")); // Fully cleaned message // Email $value_for_email = Validate::isUrlencoded($value_for_email) ? urldecode($value_for_email) : $value_for_email; diff --git a/lib/Cleantalk/ApbctWP/PluginSettingsPage/SettingsField.php b/lib/Cleantalk/ApbctWP/PluginSettingsPage/SettingsField.php index 824d3d166..fe5f8d68b 100644 --- a/lib/Cleantalk/ApbctWP/PluginSettingsPage/SettingsField.php +++ b/lib/Cleantalk/ApbctWP/PluginSettingsPage/SettingsField.php @@ -253,7 +253,8 @@ private function getRadioChildrenChunk($option) public function anyCacheDetectedInEnvironment() { - return apbct_is_varnish_cache_exists() || apbct_is_advanced_cache_exists() || apbct_is_10web_booster_exists() || apbct_is_cache_plugins_exists(); + global $apbct; + return $apbct->isAltSessionsRequired(); } /** @@ -412,7 +413,7 @@ private function getInputText() $data = [ 'name' => isset($this->params['name']) ? $this->params['name'] : '', 'type' => isset($this->params['type']) ? $this->params['type'] : '', - 'value' => $this->value, + 'value' => esc_attr(is_array($this->value) ? implode(', ', $this->value) : (string)$this->value), 'placeholder' => isset($this->params['placeholder']) ? 'placeholder="' . $this->params['placeholder'] . '"' : '', 'disabled' => $this->disabled_string, 'required' => isset($this->params['required']) && $this->params['required'] ? 'required="required"' : '', @@ -480,7 +481,16 @@ class="apbct_setting_{{type}} apbct_setting---{{name}}" */ private function getInputTextarea() { - $title_layout = '

{{title}} {{popup_description}}

'; + $title_class = 'apbct_settings-field_title apbct_settings-field_title--{{type}}'; + if ( $this->description_popup !== '' ) { + $title_class .= ' apbct_settings-field_title--with-help'; + } + $title_layout = '

{{title}} {{popup_description}}

'; + + $raw_value = empty($this->value) ? TT::getArrayValueAsString($this->params, 'value') : $this->value; + if (is_array($raw_value)) { + $raw_value = implode(', ', $raw_value); + } $data = [ 'title' => isset($this->params['title']) ? $this->params['title'] : '', @@ -491,7 +501,7 @@ private function getInputTextarea() 'disabled' => $this->disabled_string, 'required' => isset($this->params['required']) && $this->params['required'] ? 'required="required"' : '', 'childrens' => isset($this->params['childrens']) ? 'onchange="apbctSettingsDependencies(\'' . $this->children_string . '\')" ' : '', - 'value' => empty($this->value) ? TT::getArrayValueAsString($this->params, 'value') : $this->value, + 'value' => esc_textarea((string)$raw_value), ]; $layout = ''; @@ -519,7 +529,7 @@ private function getInputColor() $data = [ 'name' => isset($this->params['name']) ? $this->params['name'] : '', 'type' => isset($this->params['type']) ? $this->params['type'] : '', - 'value' => $this->value, + 'value' => esc_attr(is_array($this->value) ? implode(', ', $this->value) : (string)$this->value), 'disabled' => $this->disabled_string, 'required' => isset($this->params['required']) && $this->params['required'] ? 'required="required"' : '', 'childrens' => isset($this->params['childrens']) ? 'onchange="apbctSettingsDependencies(\'' . $this->children_string . '\')" ' : '', diff --git a/lib/Cleantalk/ApbctWP/RemoteCalls.php b/lib/Cleantalk/ApbctWP/RemoteCalls.php index a14c19c3a..eccdff050 100644 --- a/lib/Cleantalk/ApbctWP/RemoteCalls.php +++ b/lib/Cleantalk/ApbctWP/RemoteCalls.php @@ -116,6 +116,31 @@ private static function isAllowedWithoutToken($rc) return in_array($rc, self::$allowedActionsWithoutToken, true); } + /** + * Delay to wait before the remote call is passed to the host. + * + * Only the whitelisted actions are allowed to delay, and the delay itself is limited + * by self::MAX_DELAY. + * + * @param string $action Remote call action name, without the "action__" prefix + * @param mixed $delay Delay as it came in the request + * + * @return int|null Seconds to sleep, null when the call must be performed without a delay + * @psalm-return int<0, max>|null + */ + private static function getDelayForAction($action, $delay) + { + if ( ! $delay || ! in_array(strtolower($action), self::$allowedActionsWithDelay, true) ) { + return null; + } + + $delay = TT::toInt($delay); + $delay = max($delay, 0); + $delay = min($delay, self::MAX_DELAY); + + return $delay; + } + public static function checkWithoutToken() { global $apbct; @@ -215,18 +240,13 @@ public static function perform() // Flag to let plugin know that Remote Call is running. $apbct->rc_running = true; + $raw_action = $action; $action = 'action__' . $action; if ( method_exists(__CLASS__, $action) ) { // Delay before perform action - only for whitelisted actions - $current_action = strtolower(Request::getString('spbc_remote_call_action')); - if ( - Request::get('delay') && - in_array($current_action, self::$allowedActionsWithDelay, true) - ) { - $delay = Request::getInt('delay'); - $delay = max($delay, 0); - $delay = min($delay, self::MAX_DELAY); + $delay = self::getDelayForAction($raw_action, Request::get('delay')); + if ( ! is_null($delay) ) { sleep($delay); $params = $_REQUEST; unset($params['delay']); @@ -399,15 +419,6 @@ public static function action__activate_plugin() // phpcs:ignore PSR1.Methods.Ca return apbct_rc__activate_plugin(Request::get('plugin')); } - /** - * Update settings. - * @deprecated Since 6.85, see https://app.doboard.com/1/task/36680 - */ - public static function action__update_settings() // phpcs:ignore PSR1.Methods.CamelCapsMethodName.NotCamelCaps - { - return apbct_rc__update_settings($_REQUEST); - } - /** * Deactivate plugin */ @@ -524,7 +535,7 @@ public static function action__post_api_key() // phpcs:ignore PSR1.Methods.Camel header("Content-Type: application/json"); } - $key = trim(Request::getString('api_key')); + $key = trim(Request::getString('api_key'), " \n\r\t\v\x00"); if ( ! apbct_api_key__is_correct($key) ) { die(json_encode(['FAIL' => ['error' => 'Api key is incorrect']])); } diff --git a/lib/Cleantalk/ApbctWP/RestController.php b/lib/Cleantalk/ApbctWP/RestController.php index 11e07e1c6..41682a0f3 100644 --- a/lib/Cleantalk/ApbctWP/RestController.php +++ b/lib/Cleantalk/ApbctWP/RestController.php @@ -41,7 +41,9 @@ public function register_routes() // phpcs:ignore PSR1.Methods.CamelCapsMethodNa 'required' => true, ), ), - 'permission_callback' => '__return_true', + 'permission_callback' => function (WP_REST_Request $request) { + return (bool) wp_verify_nonce(TT::toString($request->get_header('x_wp_nonce')), 'wp_rest'); + }, ) )); diff --git a/lib/Cleantalk/ApbctWP/ServerRequirementsChecker/ServerRequirementsChecker.php b/lib/Cleantalk/ApbctWP/ServerRequirementsChecker/ServerRequirementsChecker.php index 555ffebab..6c36a1fd3 100644 --- a/lib/Cleantalk/ApbctWP/ServerRequirementsChecker/ServerRequirementsChecker.php +++ b/lib/Cleantalk/ApbctWP/ServerRequirementsChecker/ServerRequirementsChecker.php @@ -197,7 +197,7 @@ public function checkRequirements() */ private function normalizeMemoryLimit($val) { - $val = trim($val); + $val = trim($val, " \n\r\t\v\x00"); $last = strtolower($val[strlen($val) - 1]); $val = (int)$val; switch ($last) { diff --git a/lib/Cleantalk/ApbctWP/State.php b/lib/Cleantalk/ApbctWP/State.php index e0d637726..92b1cbd0d 100644 --- a/lib/Cleantalk/ApbctWP/State.php +++ b/lib/Cleantalk/ApbctWP/State.php @@ -94,6 +94,7 @@ class State extends \Cleantalk\Common\State 'data__email_decoder_obfuscation_custom_text' => '', 'data__email_decoder_encode_phone_numbers' => 0, 'data__email_decoder_encode_email_addresses' => 1, + 'data__email_decoder_excluded_strings' => '', 'data__wc_store_blocked_orders' => 0, // Exclusions @@ -285,7 +286,6 @@ class State extends \Cleantalk\Common\State //Common 'close_renew_banner' => array('last_call' => 0, 'cooldown' => 0), 'check_website' => array('last_call' => 0, 'cooldown' => 0), - 'update_settings' => array('last_call' => 0, 'cooldown' => 0), 'run_service_template_get' => array('last_call' => 0, 'cooldown' => 60), 'license_update' => array('last_call' => 0, 'cooldown' => 0), diff --git a/lib/Cleantalk/ApbctWP/UpdatePlugin/DbColumnCreator.php b/lib/Cleantalk/ApbctWP/UpdatePlugin/DbColumnCreator.php index 3ae812be2..dba8eb2ff 100644 --- a/lib/Cleantalk/ApbctWP/UpdatePlugin/DbColumnCreator.php +++ b/lib/Cleantalk/ApbctWP/UpdatePlugin/DbColumnCreator.php @@ -134,9 +134,9 @@ private function updateIndexes($schema_indexes_raw, $db_column_names, &$errors) if (!isset($match[1], $match[3])) { continue; } - $keyword = strtoupper(trim($match[1])); + $keyword = strtoupper(trim($match[1], " \n\r\t\v\x00")); $explicit_name = !empty($match[2]) ? $match[2] : ''; - $columns_raw = trim($match[3]); + $columns_raw = trim($match[3], " \n\r\t\v\x00"); // Skip PRIMARY KEY as it should already exist if table has primary key if (strpos($keyword, 'PRIMARY') !== false) { @@ -256,7 +256,7 @@ private function updateIndexes($schema_indexes_raw, $db_column_names, &$errors) if (isset($schema_indexes[$index_name])) { $index_def = $schema_indexes[$index_name]; if (preg_match('/\(([^)]+)\)/', $index_def, $col_match) && isset($col_match[1])) { - $columns = trim($col_match[1]); + $columns = trim($col_match[1], " \n\r\t\v\x00"); $add_type = (stripos($index_def, 'UNIQUE') !== false) ? 'UNIQUE INDEX' : 'INDEX'; $sql = "ALTER TABLE `$this->dbTableName` ADD $add_type `$index_name` ($columns)"; $result = $wpdb->query($sql); @@ -293,7 +293,7 @@ private function updateIndexes($schema_indexes_raw, $db_column_names, &$errors) // Create proper SQL: ALTER TABLE `table` ADD INDEX `name` (`column`) // Parse the index definition to extract columns if (preg_match('/\(([^)]+)\)/', $index_def, $col_match) && isset($col_match[1])) { - $columns = trim($col_match[1]); + $columns = trim($col_match[1], " \n\r\t\v\x00"); $add_type = (stripos($index_def, 'UNIQUE') !== false) ? 'UNIQUE INDEX' : 'INDEX'; $sql = "ALTER TABLE `$this->dbTableName` ADD $add_type `$diff_index_name` ($columns)"; $result = $wpdb->query($sql); diff --git a/lib/Cleantalk/ApbctWP/Variables/AltSessions.php b/lib/Cleantalk/ApbctWP/Variables/AltSessions.php index 67eba3104..9e68edeb3 100644 --- a/lib/Cleantalk/ApbctWP/Variables/AltSessions.php +++ b/lib/Cleantalk/ApbctWP/Variables/AltSessions.php @@ -29,9 +29,9 @@ class AltSessions 'ct_has_key_up' => 'bool', 'ct_has_scrolled' => 'bool', 'ct_mouse_moved' => 'bool', - 'wordpress_apbct_antibot' => 'hash', + 'apbct_antibot' => 'hash', 'apbct_anticrawler_passed' => 'int', - 'apbct_antiflood_passed' => 'int', + 'apbct_antiflood_passed' => 'hash', 'ct_sfw_pass_key' => 'string', 'ct_sfw_passed' => 'int', 'ct_gathering_loaded' => 'bool', diff --git a/lib/Cleantalk/ApbctWP/Variables/Cookie.php b/lib/Cleantalk/ApbctWP/Variables/Cookie.php index 3a6c3c98b..a7056c95b 100644 --- a/lib/Cleantalk/ApbctWP/Variables/Cookie.php +++ b/lib/Cleantalk/ApbctWP/Variables/Cookie.php @@ -13,7 +13,7 @@ class Cookie extends \Cleantalk\Variables\Cookie public static $force_to_use_alternative_cookies = array( 'ct_sfw_pass_key', 'ct_sfw_passed', - 'wordpress_apbct_antibot', + 'apbct_antibot', 'apbct_anticrawler_passed', 'apbct_antiflood_passed', 'apbct_email_encoder_passed', diff --git a/lib/Cleantalk/Common/ContactsEncoder/ContactsEncoder.php b/lib/Cleantalk/Common/ContactsEncoder/ContactsEncoder.php index 991461442..beda1fafc 100644 --- a/lib/Cleantalk/Common/ContactsEncoder/ContactsEncoder.php +++ b/lib/Cleantalk/Common/ContactsEncoder/ContactsEncoder.php @@ -2,6 +2,8 @@ namespace Cleantalk\Common\ContactsEncoder; +use Cleantalk\Common\Antispam\Cleantalk; +use Cleantalk\Common\Antispam\CleantalkRequest; use Cleantalk\Common\ContactsEncoder\Helper\ContactsEncoderHelper; use Cleantalk\Common\ContactsEncoder\Dto\Params; use Cleantalk\Common\ContactsEncoder\Encoder\Encoder; @@ -12,8 +14,12 @@ /** * Contacts Encoder common class. */ -abstract class ContactsEncoder +class ContactsEncoder { + const VERSION = '2.1.1'; + + protected $api_key; + /** * @var Encoder */ @@ -44,8 +50,13 @@ abstract class ContactsEncoder const EMAIL_PATTERN = '[_A-Za-z0-9-\.]+@[_A-Za-z0-9-\.]+\.[A-Za-z]{2,}\b'; const EMAIL_PATTERN_DOMAIN_CATCHING = '[_A-Za-z0-9-\.]+@[_A-Za-z0-9-\.]+(\.[A-Za-z]{2,}\b)'; const PHONE_NUMBER = '\+\d{8,12}'; + /** + * URI schemes are case-insensitive (RFC 3986). Clients often write Mailto:/Tel:. + */ + const MAILTO_SCHEME_PATTERN = '(?i:mailto):'; + const TEL_SCHEME_PATTERN = '(?i:tel):'; const PHONE_NUMBERS_PATTERNS = [ - '(tel:' . self::PHONE_NUMBER . ')', // tel:+XXXXXXXXXX + '(' . self::TEL_SCHEME_PATTERN . self::PHONE_NUMBER . ')', // tel:+XXXXXXXXXX '([\+][\s-]?\(?\d[\d\s\-()]{7,}\d)', // +X XXX XXXXXXX, +X(XXX)XXXXX, etc. '(\(\d{3}\)\s?\d{3}-\d{4})', // (XXX) XXX-XXXX, (XXX) XXX XXXX '(\+\d{1,3}\.\d{1,3}\.((\d{3}\.\d{4})|\d{7})(?![\w.]))', // +X?.XX?.XXX.XXXX @@ -57,17 +68,17 @@ abstract class ContactsEncoder protected $aria_regex; /** - * @var string example: '/(mailto\:\b[_A-Za-z0-9-\.]+@[_A-Za-z0-9-\.]+\.[A-Za-z]{2,}\b)|(\b[_A-Za-z0-9-\.]+@[_A-Za-z0-9-\.]+(\.[A-Za-z]{2,}\b))/' + * @var string example: '/((?i:mailto):\b[_A-Za-z0-9-\.]+@[_A-Za-z0-9-\.]+\.[A-Za-z]{2,}\b)|(\b[_A-Za-z0-9-\.]+@[_A-Za-z0-9-\.]+(\.[A-Za-z]{2,}\b))/' */ protected $global_email_pattern; /** - * @var string example: '/(tel:\+\d{8,12})|([\+][\s-]?\(?\d[\d\s\-()]{7,}\d)|(\(\d{3}\)\s?\d{3}-\d{4})|(\+\d{1,3}\.\d{1,3}\.((\d{3}\.\d{4})|\d{7})(?![\w.]))'/' + * @var string example: '/((?i:tel):\+\d{8,12})|([\+][\s-]?\(?\d[\d\s\-()]{7,}\d)|(\(\d{3}\)\s?\d{3}-\d{4})|(\+\d{1,3}\.\d{1,3}\.((\d{3}\.\d{4})|\d{7})(?![\w.]))/' */ protected $global_phones_pattern; /** - * @var string example: '/mailto\:(\b[_A-Za-z0-9-\.]+@[_A-Za-z0-9-\.]+\.[A-Za-z]{2,})/' + * @var string example: '/(?i:mailto):(\b[_A-Za-z0-9-\.]+@[_A-Za-z0-9-\.]+\.[A-Za-z]{2,})/' */ protected $global_mailto_pattern; @@ -77,13 +88,7 @@ abstract class ContactsEncoder protected $plain_email_pattern; /** - * @var string example: '/\b[_A-Za-z0-9-\.]+@[_A-Za-z0-9-\.]+\.[A-Za-z]{2,}/' - * @ToDo Is this regular expression needed? A little different against `$plain_email_pattern`. - */ - protected $plain_email_pattern_without_capturing; - - /** - * @var string example: '/tel:(\+\d{8,12})/' + * @var string example: '/(?i:tel):(\+\d{8,12})/' * @ToDo Is this regexp is actual and right? */ protected $global_tel_pattern; @@ -133,6 +138,10 @@ abstract class ContactsEncoder */ protected $is_logged_in = false; + protected $request_result_comment; + + protected $decoded_contacts_array = []; + protected static $instance; public function __construct() @@ -178,6 +187,7 @@ public function dropInstance() */ protected function init(Params $params) { + $this->api_key = $params->api_key; $this->exclusions = new ExclusionsService($params); $this->encoder = new Encoder(md5($params->api_key)); $this->helper = new ContactsEncoderHelper(); @@ -197,12 +207,11 @@ private function prepareRegularExpressions() { $this->aria_regex = self::ARIA_LABEL_PATTERN; - $this->global_email_pattern = '/(mailto\:\b' . self::EMAIL_PATTERN . ')|(\b' . self::EMAIL_PATTERN_DOMAIN_CATCHING . ')/'; + $this->global_email_pattern = '/(' . self::MAILTO_SCHEME_PATTERN . '\b' . self::EMAIL_PATTERN . ')|(\b' . self::EMAIL_PATTERN_DOMAIN_CATCHING . ')/'; $this->global_phones_pattern = '/' . implode('|', self::PHONE_NUMBERS_PATTERNS) . '/'; - $this->global_mailto_pattern = '/mailto\:(' . self::EMAIL_PATTERN . ')/'; + $this->global_mailto_pattern = '/' . self::MAILTO_SCHEME_PATTERN . '(' . self::EMAIL_PATTERN . ')/'; $this->plain_email_pattern = '/(\b' . self::EMAIL_PATTERN . '\b)/'; - $this->plain_email_pattern_without_capturing = '/\b' . self::EMAIL_PATTERN . '/'; - $this->global_tel_pattern = '/tel:(' . self::PHONE_NUMBER . ')/'; + $this->global_tel_pattern = '/' . self::TEL_SCHEME_PATTERN . '(' . self::PHONE_NUMBER . ')/'; } /** @@ -229,6 +238,7 @@ public function runEncoding($content = '') public function runDecoding($encoded_contacts_data) { $decoded_strings = $this->decodeContactData($encoded_contacts_data); + $this->decoded_contacts_array = $decoded_strings; // @ToDo Check connections errors during checkRequest and return success:false return json_encode([ 'success' => true, @@ -268,6 +278,10 @@ public function modifyContent($content, $skip_exclusions = false) $this->do_encode_phones && $content = $this->modifyGlobalPhoneNumbers($content); + if ( $this->do_encode_emails || $this->do_encode_phones ) { + $content = $this->handleAriaLabelContent($content, true); + } + return $content; } @@ -279,78 +293,58 @@ public function modifyContent($content, $skip_exclusions = false) */ public function modifyGlobalEmails($content) { - $replacing_result = ''; - - if ( version_compare(phpversion(), '7.4.0', '>=') ) { - $replacing_result = preg_replace_callback($this->global_email_pattern, function ($matches) use ($content) { - if ( isset($matches[3][0], $matches[0][0]) && in_array(strtolower($matches[3][0]), ['.jpg', '.jpeg', '.png', '.gif', '.svg', '.webp']) ) { - return $matches[0][0]; - } + $owns_aria_protection = empty($this->aria_placeholders); + if ( $owns_aria_protection ) { + $content = $this->handleAriaLabelContent($content); + } - //chek if email is placed in excluded attributes and return unchanged if so - if ( isset($matches[0][0]) && $this->helper->hasAttributeExclusions($matches[0][0], $this->temp_content) ) { - return $matches[0][0]; - } + $this->temp_content = $content; - // skip encoding if the content in script tag - if ( isset($matches[0][0]) && $this->helper->isInsideScriptTag($matches[0][0], $content) ) { - return $matches[0][0]; - } + $match_cursor = 0; + $replacing_result = preg_replace_callback($this->global_email_pattern, function ($matches) use (&$match_cursor) { + if ( ! isset($matches[0]) ) { + return ''; + } - if ( isset($matches[0][0]) && $this->helper->isMailto($matches[0][0]) ) { - return $this->encodeMailtoLinkV2($matches[0], $content); - } + $position = $this->advanceMatchCursor($matches[0], $match_cursor); - if ( - isset($matches[0]) && - is_array($matches[0]) && - $this->helper->isMailtoAdditionalCopy($matches[0], $content) - ) { - return ''; - } + if ( $this->exclusions->isContactExcluded($matches[0]) ) { + return $matches[0]; + } - if ( - isset($matches[0], $matches[0][0]) && - is_array($matches[0]) && - $this->helper->isEmailInLink($matches[0], $content) - ) { - return $matches[0][0]; - } + if ( isset($matches[3]) && in_array(strtolower($matches[3]), ['.jpg', '.jpeg', '.png', '.gif', '.svg', '.webp']) ) { + return $matches[0]; + } - if ( isset($matches[0][0]) ) { - return $this->encodePlainEmail($matches[0][0]); - } + //chek if email is placed in excluded attributes and return unchanged if so + if ( $this->helper->hasAttributeExclusions($matches[0], $this->temp_content, $position) ) { + return $matches[0]; + } - return ''; - }, $content, -1, $count, PREG_OFFSET_CAPTURE); - } + // skip encoding if the content in script tag + if ( $this->helper->isInsideScriptTag($matches[0], $this->temp_content, $position) ) { + return $matches[0]; + } - if ( version_compare(phpversion(), '7.4.0', '<') ) { - $replacing_result = preg_replace_callback($this->global_email_pattern, function ($matches) { - if ( isset($matches[3]) && in_array(strtolower($matches[3]), ['.jpg', '.jpeg', '.png', '.gif', '.svg', '.webp']) && isset($matches[0]) ) { - return $matches[0]; - } + if ( $this->helper->isInsideOptionTag($matches[0], $this->temp_content, $position) ) { + return $matches[0]; + } - //chek if email is placed in excluded attributes and return unchanged if so - if ( isset($matches[0]) && $this->helper->hasAttributeExclusions($matches[0], $this->temp_content) ) { - return $matches[0]; - } + if ( $this->helper->isMailtoAdditionalCopy($matches[0], $this->temp_content, $position) ) { + return ''; + } - if ( isset($matches[0]) && $this->helper->isMailto($matches[0]) ) { - return $this->encodeMailtoLink($matches[0]); - } + if ( $this->helper->isMailto($matches[0]) ) { + return $this->encodeMailtoLink($matches[0]); + } - if ( isset($matches[0]) ) { - return $this->encodePlainEmail($matches[0]); - } + return $this->encodePlainEmail($matches[0]); + }, $content); - return ''; - }, $content); + if ( $owns_aria_protection ) { + $replacing_result = $this->handleAriaLabelContent($replacing_result, true); } - // modify content to turn back aria-label - $replacing_result = $this->handleAriaLabelContent($replacing_result, true); - //please keep this var (do not simplify the code) for further debug return $replacing_result; } @@ -364,98 +358,85 @@ public function modifyGlobalEmails($content) */ public function modifyGlobalPhoneNumbers($content) { - $phones_pattern = $this->global_phones_pattern; - $replacing_result = ''; - - if ( version_compare(phpversion(), '7.4.0', '>=') ) { - $replacing_result = preg_replace_callback( - $phones_pattern, - function ($matches) use ($content) { - if ( isset($matches[0]) ) { - $first_group = $matches[0]; - } else { - return ''; - } - - if ( isset($first_group[0]) ) { - $second_group = $first_group[0]; - } else { - return ''; - } - - if (is_array($first_group) && $this->helper->isTelTag($second_group) ) { - return $this->encodeTelLinkV2($first_group, $content); - } - //symbols clearance - $item_length = strlen(str_replace([' ', '(', ')', '-', '+', '.'], '', $second_group)); - //check length - if ( $item_length > 12 || $item_length < 8 ) { - return $second_group; - } - //check attribute exclusions - if ( $this->helper->hasAttributeExclusions($second_group, $this->temp_content) ) { - return $second_group; - } - //check if in script - if ( $this->helper->isInsideScriptTag($second_group, $content) ) { - return $second_group; - } - //do encode - return $this->encodeAny( - $second_group, - $this->global_obfuscation_mode, - $this->global_replacing_text, - true - ); - }, - $content, - -1, - $count, - PREG_OFFSET_CAPTURE - ); + $owns_aria_protection = empty($this->aria_placeholders); + if ( $owns_aria_protection ) { + $content = $this->handleAriaLabelContent($content); } - if ( version_compare(phpversion(), '7.4.0', '<') ) { - $replacing_result = preg_replace_callback( - $phones_pattern, - function ($matches) { - if ( isset($matches[0]) ) { - if ( $this->helper->isTelTag($matches[0]) ) { - return $this->encodeTelLink($matches[0]); - } - - $item_length = strlen(str_replace([' ', '(', ')', '-', '+', '.'], '', $matches[0])); - if ( $item_length > 12 || $item_length < 8 ) { - return $matches[0]; - } - - if ( $this->helper->hasAttributeExclusions($matches[0][0], $this->temp_content) ) { - return $matches[0]; - } - } - - if ( isset($matches[0]) ) { - return $this->encodeAny( - $matches[0], - $this->global_obfuscation_mode, - $this->global_replacing_text, - true - ); - } + $this->temp_content = $content; + $phones_pattern = $this->global_phones_pattern; + $match_cursor = 0; + $replacing_result = preg_replace_callback( + $phones_pattern, + function ($matches) use (&$match_cursor) { + if ( ! isset($matches[0]) ) { return ''; - }, - $content - ); - } + } - // modify content to turn back aria-label - $replacing_result = $this->handleAriaLabelContent($replacing_result, true); + $position = $this->advanceMatchCursor($matches[0], $match_cursor); + + if ( $this->exclusions->isContactExcluded($matches[0]) ) { + return $matches[0]; + } + + if ( $this->helper->isTelTag($matches[0]) ) { + return $this->encodeTelLink($matches[0]); + } + + // symbols clearance + $item_length = strlen(str_replace([' ', '(', ')', '-', '+', '.'], '', $matches[0])); + + // check length + if ( $item_length > 12 || $item_length < 8 ) { + return $matches[0]; + } + + // check attribute exclusions + if ( $this->helper->hasAttributeExclusions($matches[0], $this->temp_content, $position) ) { + return $matches[0]; + } + + // check if in script + if ( $this->helper->isInsideScriptTag($matches[0], $this->temp_content, $position) ) { + return $matches[0]; + } + + return $this->encodeAny( + $matches[0], + $this->global_obfuscation_mode, + $this->global_replacing_text, + true + ); + }, + $content + ); + + if ( $owns_aria_protection ) { + $replacing_result = $this->handleAriaLabelContent($replacing_result, true); + } //please keep this var (do not simplify the code) for further debug return $replacing_result; } + /** + * Advance the left-to-right cursor so repeated contacts use their own offset. + * + * @param string $match + * @param int $cursor + * @return int|false + */ + private function advanceMatchCursor($match, &$cursor) + { + $position = strpos($this->temp_content, $match, $cursor); + if ( $position !== false ) { + $cursor = $position + strlen($match); + } + + return $position; + } + /* * =============== ENCODE ENTITIES =============== */ @@ -520,7 +501,7 @@ protected function encodeAny($string, $mode = Params::OBFUSCATION_MODE_BLUR, $re } /** - * Method to process mailto: links. For PHP < 7.4 + * Method to process mailto: links. * * @param string $mailto_link_str * @@ -537,40 +518,7 @@ private function encodeMailtoLink($mailto_link_str) } }, $matches[1]); } - $mailto_link_str = str_replace('mailto:', '', $mailto_link_str); - $encoded = $this->encoder->encodeString($mailto_link_str); - - $text = isset($mailto_inner_text) ? $mailto_inner_text : $mailto_link_str; - - return 'mailto:' . $text . '" data-original-string="' . $encoded . '" title="' . htmlspecialchars($this->getTooltip(), ENT_QUOTES, 'UTF-8'); - } - - /** - * Method to process mailto: links. Use this only for PHP 7.4+ - * - * @param $match array - * @param $content string - * - * @return string - */ - private function encodeMailtoLinkV2($match, $content) - { - $position = $match[1]; - $q_position = $position + strcspn($content, '\'"', $position); - $mailto_link_str = substr($content, $position, $q_position - $position); - // Get inner tag text and place it in $matches[1] - preg_match($this->global_mailto_pattern, $mailto_link_str, $matches); - if ( isset($matches[1]) ) { - $mailto_inner_text = preg_replace_callback($this->plain_email_pattern_without_capturing, function ($matches) { - if ( isset($matches[0]) ) { - return $this->getObfuscatedEmailString($matches[0]); - } - - return ''; - }, $matches[1]); - } - - $mailto_link_str = str_replace('mailto:', '', $mailto_link_str); + $mailto_link_str = preg_replace('/^mailto:/i', '', $mailto_link_str); $encoded = $this->encoder->encodeString($mailto_link_str); $text = isset($mailto_inner_text) ? $mailto_inner_text : $mailto_link_str; @@ -579,7 +527,7 @@ private function encodeMailtoLinkV2($match, $content) } /** - * Method to process tel: links. For PHP < 7.4 + * Method to process tel: links. * * @param string $tel_link_str * @@ -590,53 +538,17 @@ private function encodeTelLink($tel_link_str) // Get inner tag text and place it in $matches[1] preg_match($this->global_tel_pattern, $tel_link_str, $matches); if ( isset($matches[1]) ) { - $mailto_inner_text = preg_replace_callback('/' . self::PHONE_NUMBER . '/', function ($matches) { + $tel_inner_text = preg_replace_callback('/' . self::PHONE_NUMBER . '/', function ($matches) { if (isset($matches[0])) { $obfuscator = new Obfuscator(); return $obfuscator->processPhone($matches[0]); } }, $matches[1]); } - $tel_link_str = str_replace('tel:', '', $tel_link_str); + $tel_link_str = preg_replace('/^tel:/i', '', $tel_link_str); $encoded = $this->encoder->encodeString($tel_link_str); - $text = isset($mailto_inner_text) ? $mailto_inner_text : $tel_link_str; - - return 'tel:' . $text . '" data-original-string="' . $encoded . '" title="' . htmlspecialchars($this->getTooltip(), ENT_QUOTES, 'UTF-8'); - } - - /** - * Method to process tel: links. Use this only for PHP 7.4+ - * - * @param array $match - * @param string $content - * - * @return string - */ - private function encodeTelLinkV2($match, $content) - { - $position = !empty($match[1]) ? (int)$match[1] : null; - if (null === $position) { - return $content; - } - $q_position = $position + strcspn($content, '\'"', $position); - $tel_link_string = substr($content, $position, $q_position - $position); - // Get inner tag text and place it in $matches[1] - preg_match($this->global_tel_pattern, $tel_link_string, $matches); - if ( isset($matches[1]) ) { - $tel_inner_text = preg_replace_callback('/' . self::PHONE_NUMBER . '/', function ($matches) { - if ( isset($matches[0]) ) { - $obfuscator = new Obfuscator(); - return $obfuscator->processPhone($matches[0]); - } - return ''; - }, $matches[1]); - } - - $tel_link_string = str_replace('tel:', '', $tel_link_string); - $encoded = $this->encoder->encodeString($tel_link_string); - - $text = isset($tel_inner_text) ? $tel_inner_text : $tel_link_string; + $text = isset($tel_inner_text) ? $tel_inner_text : $tel_link_str; return 'tel:' . $text . '" data-original-string="' . $encoded . '" title="' . htmlspecialchars($this->getTooltip(), ENT_QUOTES, 'UTF-8'); } @@ -802,9 +714,57 @@ public function decodeContactData($encoded_contacts_array) * * @return bool returns json string to the JS */ - abstract protected function checkRequest(); + protected function checkRequest() + { + $event_javascript_data = ''; + $event_token = ''; + if ( isset($_POST['event_token']) && is_string($_POST['event_token']) ) { + $event_token = $_POST['event_token']; + } elseif ( isset($_POST['event_javascript_data']) && is_string($_POST['event_javascript_data']) ) { + $event_javascript_data = $_POST['event_javascript_data']; + } + + $params = array( + 'auth_key' => $this->api_key, // Access key + 'agent' => 'contacts_encoder_lib_' . self::VERSION, + 'event_token' => $event_token, // Unique event ID + 'event_javascript_data' => $event_javascript_data, // JSON-string params to analysis + 'sender_ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '', + 'event_type' => 'CONTACT_DECODING', // 'GENERAL_BOT_CHECK' || 'CONTACT_DECODING' + 'message_to_log' => json_encode(array_values($this->decoded_contacts_array), JSON_FORCE_OBJECT), // Custom message + 'page_url' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '', + 'sender_info' => array( + 'site_referrer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '', + ), + ); + + $ct_request = new CleantalkRequest($params); + + $ct = new Cleantalk(); + + $ct->server_url = 'https://moderate.cleantalk.org'; + $ct->work_url = 'https://moderate.cleantalk.org'; + $api_response = $ct->checkBot($ct_request); + + // Allow to see the decoded contact if error occurred. + if ( ! empty($api_response->errstr)) { + $this->request_result_comment = $api_response->errstr; + return true; + } + + $stub_comment = $api_response->allow + ? 'Allowed' + : 'Blocked'; - abstract protected function getCheckRequestComment(); + $this->request_result_comment = ! empty($api_response->comment) ? $api_response->comment : $stub_comment; + + return $api_response->allow === 1; + } + + protected function getCheckRequestComment() + { + return $this->request_result_comment; + } /** * @param $decoded_emails_array @@ -961,11 +921,15 @@ private function generateAriaLabelPlaceholder() */ private function getSecureRandomBytes($length) { + if ( !is_int($length) || $length < 1 ) { + return null; + } + if ( function_exists('random_bytes') ) { try { // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.random_bytesFound $bytes = random_bytes($length); - if ( is_string($bytes) && strlen($bytes) === $length ) { + if ( strlen($bytes) === $length ) { return $bytes; } } catch ( \Exception $e ) { @@ -974,8 +938,9 @@ private function getSecureRandomBytes($length) } if ( function_exists('openssl_random_pseudo_bytes') ) { - $bytes = openssl_random_pseudo_bytes($length); - if ( is_string($bytes) && strlen($bytes) === $length ) { + $crypto_strong = false; + $bytes = openssl_random_pseudo_bytes($length, $crypto_strong); + if ( $crypto_strong && is_string($bytes) && strlen($bytes) === $length ) { return $bytes; } } diff --git a/lib/Cleantalk/Common/ContactsEncoder/Dto/Params.php b/lib/Cleantalk/Common/ContactsEncoder/Dto/Params.php index e73403182..f0e4acff3 100644 --- a/lib/Cleantalk/Common/ContactsEncoder/Dto/Params.php +++ b/lib/Cleantalk/Common/ContactsEncoder/Dto/Params.php @@ -19,4 +19,11 @@ class Params public $obfuscation_text = 'hidden contact data'; public $do_encode_emails = 1; public $do_encode_phones = 0; + + /** + * Emails, phones or text fragments that must never be encoded. + * + * @var string[] + */ + public $excluded_strings = array(); } diff --git a/lib/Cleantalk/Common/ContactsEncoder/Exclusions/ExclusionsService.php b/lib/Cleantalk/Common/ContactsEncoder/Exclusions/ExclusionsService.php index 39c1dbf31..692324a17 100644 --- a/lib/Cleantalk/Common/ContactsEncoder/Exclusions/ExclusionsService.php +++ b/lib/Cleantalk/Common/ContactsEncoder/Exclusions/ExclusionsService.php @@ -82,4 +82,125 @@ protected function byLoggedIn() { return $this->params->is_logged_in; } + + /** + * Split a settings textarea into unique non-empty exclusion strings (one value per line). + * + * @param string $raw + * + * @return string[] + * @psalm-suppress PossiblyUnusedMethod Public API for host apps that store the list as raw text + */ + public static function parseExcludedStrings($raw) + { + if ( ! is_string($raw) || $raw === '' ) { + return array(); + } + + $parts = preg_split('/\R+/', $raw); + if ( ! is_array($parts) ) { + return array(); + } + + $result = array(); + foreach ( $parts as $part ) { + $part = trim($part, " \n\r\t\v\x00"); + if ( $part !== '' ) { + $result[] = $part; + } + } + + return array_values(array_unique($result)); + } + + /** + * Whether a matched email or phone must stay unencoded. + * + * @param string $match + * + * @return bool + */ + public function isContactExcluded($match) + { + if ( ! is_string($match) || $match === '' ) { + return false; + } + + if ( empty($this->params->excluded_strings) || ! is_array($this->params->excluded_strings) ) { + return false; + } + + $normalized_match = $this->normalizeContactString($match); + $match_digits = $this->extractDigits($match); + + foreach ( $this->params->excluded_strings as $exclusion ) { + if ( ! is_string($exclusion) || $exclusion === '' ) { + continue; + } + + $normalized_exclusion = $this->normalizeContactString($exclusion); + if ( $normalized_exclusion === '' ) { + continue; + } + + if ( $normalized_match === $normalized_exclusion ) { + return true; + } + + if ( strpos($normalized_match, $normalized_exclusion) !== false ) { + return true; + } + + // Digit compare is for phones only. Emails with long number sequences + // must not match an excluded phone (or the other way around). + if ( + strpos($normalized_match, '@') === false + && strpos($normalized_exclusion, '@') === false + ) { + $exclusion_digits = $this->extractDigits($exclusion); + if ( + strlen($exclusion_digits) >= 8 + && strlen($match_digits) >= 8 + && ( + strpos($match_digits, $exclusion_digits) !== false + || strpos($exclusion_digits, $match_digits) !== false + ) + ) { + return true; + } + } + } + + return false; + } + + /** + * @param string $value + * + * @return string + */ + private function normalizeContactString($value) + { + $value = trim($value, " \n\r\t\v\x00"); + if ( stripos($value, 'mailto:') === 0 ) { + $value = substr($value, 7); + } + if ( stripos($value, 'tel:') === 0 ) { + $value = substr($value, 4); + } + + return strtolower(trim($value, " \n\r\t\v\x00")); + } + + /** + * @param string $value + * + * @return string + */ + private function extractDigits($value) + { + $digits = preg_replace('/\D+/', '', $value); + + return is_string($digits) ? $digits : ''; + } } diff --git a/lib/Cleantalk/Common/ContactsEncoder/Helper/ContactsEncoderHelper.php b/lib/Cleantalk/Common/ContactsEncoder/Helper/ContactsEncoderHelper.php index 0c6100169..8b9a91288 100644 --- a/lib/Cleantalk/Common/ContactsEncoder/Helper/ContactsEncoderHelper.php +++ b/lib/Cleantalk/Common/ContactsEncoder/Helper/ContactsEncoderHelper.php @@ -13,6 +13,7 @@ class ContactsEncoderHelper */ private $attribute_exclusions_signs = array( 'input' => array('placeholder', 'value', 'data-mask'), + 'option' => array('value'), 'sc-customer-email' => array('placeholder', 'value'), 'img' => array('alt', 'title'), 'div' => array('data-et-multi-view'), @@ -39,7 +40,7 @@ class ContactsEncoderHelper */ public function isMailto($string) { - return strpos($string, 'mailto:') !== false; + return stripos($string, 'mailto:') !== false; } /** @@ -51,22 +52,23 @@ public function isMailto($string) */ public function isTelTag($string) { - return strpos($string, 'tel:') !== false; + return stripos($string, 'tel:') !== false; } /** * Checking if the string contains mailto: link * - * @param array $match + * @param string $email * @param string $content + * @param int|false|null $position Known match offset; null looks up the first occurrence * * @return bool */ - public function isMailtoAdditionalCopy($match, $content) + public function isMailtoAdditionalCopy($email, $content, $position = null) { - $position = isset($match[1]) ? (int)$match[1] : null; + $position = $this->resolveMatchPosition($email, $content, $position); - if (null === $position) { + if ($position === false) { return false; } @@ -84,41 +86,49 @@ public function isMailtoAdditionalCopy($match, $content) } /** - * Checking if email in link + * Check if the given email is inside an option element text (not attributes). * - * @param array $matches + * @param string $email * @param string $content + * @param int|false|null $position Known match offset; null looks up the first occurrence * * @return bool */ - public function isEmailInLink($matches, $content) + public function isInsideOptionTag($email, $content, $position = null) { - $email = isset($matches[0]) && is_string($matches[0]) ? $matches[0] : null; - $position = isset($matches[1]) ? (int)$matches[1] : null; + $pos = $this->resolveMatchPosition($email, $content, $position); + if ($pos === false) { + return false; + } - if (null === $position || null === $email) { + $last_option_start = strrpos(substr($content, 0, $pos), '', $last_option_start); + if ($option_tag_end === false || $pos <= $option_tag_end) { + return false; + } - if ( $href_position !== false && $href_position + 6 == $position ) { - return true; + $option_close = stripos($content, '', $last_option_start); + if ($option_close === false) { + return false; } - return strpos($email, 'mailto:') !== false; + return $pos > $option_tag_end && $pos < $option_close; } /** * Check if the given email is inside a script tag * @param string $email The email to check * @param string $content The full content + * @param int|false|null $position Known match offset; null looks up the first occurrence * @return bool */ - public function isInsideScriptTag($email, $content) + public function isInsideScriptTag($email, $content, $position = null) { - // Find position of the email in content - $pos = strpos($content, $email); + $pos = $this->resolveMatchPosition($email, $content, $position); if ($pos === false) { return false; } @@ -228,33 +238,41 @@ public function addAttributeNames(array $names) * * @param string $email_match - email * @param string $temp_content - email + * @param int|false|null $position Known match offset; null accepts any occurrence * @return bool */ - public function hasAttributeExclusions($email_match, $temp_content) + public function hasAttributeExclusions($email_match, $temp_content, $position = null) { if ( ! is_string($email_match) || $email_match === '' || ! is_string($temp_content) ) { return false; } + if ( $position !== null ) { + $position = $this->resolveMatchPosition($email_match, $temp_content, $position); + if ( $position === false ) { + return false; + } + } + $quoted_match = preg_quote($email_match, '/'); $attribute_signs = $this->getWorkingAttributeExclusionsSigns(); foreach ( $attribute_signs as $tag => $array_of_attributes ) { - if ( ! is_array($array_of_attributes) ) { + if ( ! is_string($tag) || $tag === '' || ! is_array($array_of_attributes) ) { continue; } foreach ( $array_of_attributes as $attribute ) { if ( ! is_string($attribute) || $attribute === '' ) { continue; } - if ( $this->isMatchInsideAttribute($quoted_match, $attribute, $temp_content, $tag) ) { + if ( $this->isMatchInsideAttribute($quoted_match, $attribute, $temp_content, $tag, $position) ) { return true; } } } foreach ( $this->attribute_exclusions_list as $attribute ) { - if ( $this->isMatchInsideAttribute($quoted_match, $attribute, $temp_content) ) { + if ( $this->isMatchInsideAttribute($quoted_match, $attribute, $temp_content, null, $position) ) { return true; } } @@ -288,14 +306,43 @@ private function sanitizeAttributeNames(array $names) return $result; } + /** + * @param string $needle + * @param string $haystack + * @param int|false|null $position + * @return int|false + */ + private function resolveMatchPosition($needle, $haystack, $position) + { + if ( $position === null ) { + return strpos($haystack, $needle); + } + + if ( $position === false || ! is_int($position) || $position < 0 || ! is_string($needle) || $needle === '' ) { + return false; + } + + $length = strlen($needle); + if ( $position > strlen($haystack) - $length ) { + return false; + } + + if ( substr($haystack, $position, $length) !== $needle ) { + return false; + } + + return $position; + } + /** * @param string $quoted_match * @param string $attribute * @param string $content * @param string|null $tag + * @param int|null $position * @return bool */ - private function isMatchInsideAttribute($quoted_match, $attribute, $content, $tag = null) + private function isMatchInsideAttribute($quoted_match, $attribute, $content, $tag = null, $position = null) { $quoted_attribute = preg_quote($attribute, '/'); // Always require an HTML tag so plain text like attr="..." is not treated as markup. @@ -311,6 +358,25 @@ private function isMatchInsideAttribute($quoted_match, $attribute, $content, $ta . $quoted_match . '[^"\']*\1/'; - return (bool) preg_match($pattern, $content); + if ( $position === null ) { + return (bool) preg_match($pattern, $content); + } + + if ( ! preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE) || ! isset($matches[0]) ) { + return false; + } + + foreach ( $matches[0] as $match ) { + if ( ! isset($match[0], $match[1]) ) { + continue; + } + $start = $match[1]; + $end = $start + strlen($match[0]); + if ( $position >= $start && $position < $end ) { + return true; + } + } + + return false; } } diff --git a/lib/Cleantalk/Common/ContactsEncoder/LICENSE b/lib/Cleantalk/Common/ContactsEncoder/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/lib/Cleantalk/Common/ContactsEncoder/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/lib/Cleantalk/Common/ContactsEncoder/README.MD b/lib/Cleantalk/Common/ContactsEncoder/README.MD index 08e1f5049..3f60657e3 100644 --- a/lib/Cleantalk/Common/ContactsEncoder/README.MD +++ b/lib/Cleantalk/Common/ContactsEncoder/README.MD @@ -1,40 +1,75 @@ -# Contacts Encoder - Quick Start Guide +# Contact Encoder - email obfuscation that protects email and phone from bots + +Contact Encoder is an email obfuscation library that hides email addresses and phone numbers from spam bots and scrapers while keeping them readable for real visitors. Unlike plain JavaScript obfuscation that only stops simple bots, it verifies each visitor against the CleanTalk anti-spam cloud before decoding, so smart bots are filtered too. Works with any framework or plain HTML. ## Overview -The Contacts Encoder protects email addresses and phone numbers from spam bots. It requires **4 essential components** to work properly. +The Contacts Encoder protects email addresses and phone numbers from spam bots. It requires **4 essential components** to work properly: + +1. PHP backend with encoder configuration +2. Server-side encoding of HTML content +3. Frontend CSS/JS assets +4. AJAX decode endpoint + +Since **2.0.19**, decode requests are validated via built-in `checkRequest()` → `Cleantalk::checkBot()` (`cleantalk/antispam` is installed automatically as a dependency). + +![Demo page with encoded email test cases](assets/images/demo-page.png) + +*Example: a stand-alone demo page with multiple email encoding scenarios. Click an obfuscated contact to decode it.* -## 🚀 Complete Setup in 4 Steps +## Requirements + +- PHP 7.4+ (OpenSSL recommended for encryption) +- Composer +- A valid CleanTalk access key (`api_key`) + +## Installation + +```bash +composer require cleantalk/contacts-encoder +``` -### Step 1: PHP Backend Setup +This also installs `cleantalk/antispam` (^1.6) for bot validation on decode. -#### 1.1 Configure Parameters (Params) +## Complete setup in 4 steps + +### Step 1: PHP backend setup + +#### 1.1 Configure parameters ```php use Cleantalk\Common\ContactsEncoder\Dto\Params; $params = new Params(); -$params->api_key = 'your_cleantalk_api_key'; // REQUIRED for encryption +$params->api_key = 'your_cleantalk_api_key'; // REQUIRED for encryption and checkBot $params->obfuscation_mode = Params::OBFUSCATION_MODE_BLUR; $params->do_encode_emails = true; $params->do_encode_phones = true; -$params->is_logged_in = false; // Set true for admin users +$params->is_logged_in = false; // true skips checkBot for logged-in users ``` -#### 1.2 Create Platform-Specific Class + +#### 1.2 Optional: platform-specific class + +Extend `ContactsEncoder` only when you need custom UI text. Built-in `checkRequest()` is used by default since 2.0.19. ```php -use Cleantalk\Common\ContactsEncoder\ContactsEncoder as BaseEncoder; +use Cleantalk\Common\ContactsEncoder\ContactsEncoder; +use Cleantalk\Common\ContactsEncoder\Dto\Params; -class YourPlatformContactsEncoder extends BaseEncoder +class YourPlatformContactsEncoder extends ContactsEncoder { - // REQUIRED: Add request validation - protected function checkRequest() + public static function createParams(): Params { - // Anti-Spam protection for $_POST here - return true; + $params = new Params(); + $params->api_key = 'your_cleantalk_api_key'; + $params->obfuscation_mode = Params::OBFUSCATION_MODE_BLUR; + $params->do_encode_emails = true; + $params->do_encode_phones = false; + $params->is_logged_in = false; + + return $params; } - // OPTIONAL: Customize messages protected function getTooltip() { return 'Click to decode protected contact'; @@ -42,64 +77,164 @@ class YourPlatformContactsEncoder extends BaseEncoder } ``` -### Step 2: Encoding Content +Override `checkRequest()` only if you need custom validation instead of the default `checkBot` flow. + +### Step 2: Encoding content ```php -// Initialize encoder -$encoder = YourPlatformContactsEncoder::getInstance($params); +$encoder = ContactsEncoder::getInstance($params); +// or: YourPlatformContactsEncoder::getInstance(YourPlatformContactsEncoder::createParams()); -// Process your content $protectedHtml = $encoder->runEncoding($yourHtmlContent); -// Output to browser echo $protectedHtml; ``` -### Step 3: Frontend Assets - -#### 3.1 Include CSS - -```html - -``` +### Step 3: Frontend assets -#### 3.2 Include JavaScript +Include assets from `vendor/cleantalk/contacts-encoder/assets/` at the end of ``: ```html - + + ``` -### Step 4: JavaScript Configuration +### Step 4: JavaScript configuration -#### 4.1 Create Config Object +#### 4.1 Create config object ```javascript const encoderConfig = { - // REQUIRED: AJAX endpoint decodeContactsRequest: (encodedNodes) => { return fetch('/your-ajax-endpoint', { method: 'POST', - body: encodedNodes - }).then(r => r.json()); + body: encodedNodes, + }).then((response) => response.json()); }, - // OPTIONAL: Custom texts texts: { waitForDecoding: 'Decoding contact...', - gotIt: 'Continue', - blocked: 'Access denied' + decodingProcess: 'Please wait', + gotIt: 'Got it', + clickToSelect: 'Click to select the email', + originalContactsData: 'Full address:', + blocked: 'Access denied', }, - + serviceData: { - brandName: 'Your Site Name' - } + brandName: 'Your Site Name', + }, }; ``` -### 4.2 Initialize on Frontend +#### 4.2 Initialize on frontend ```javascript -document.addEventListener('DOMContentLoaded', () => { - new ContactsEncoder(encoderConfig); -}); +new ContactsEncoder(encoderConfig); +``` + +**Important:** do **not** wrap `new ContactsEncoder()` in `DOMContentLoaded`. The library registers its own `DOMContentLoaded` listener internally. If you create the instance inside another `DOMContentLoaded` handler, click handlers may never attach. + +Load scripts at the end of ``. + +## Decode endpoint + +Create an AJAX endpoint that calls `runDecoding()`: + +```php + false, 'data' => []]); + exit; +} + +// Optional: forward bot-check fields to checkRequest() +if (!empty($payload['event_token'])) { + $_POST['event_token'] = (string) $payload['event_token']; +} +if (!empty($payload['event_javascript_data'])) { + $_POST['event_javascript_data'] = (string) $payload['event_javascript_data']; +} + +$encoder = ContactsEncoder::getInstance($params); +echo $encoder->runDecoding($payload); +``` + +### Request format + +JSON body with encoded nodes: + +```json +{ + "0": "encoded_string_1", + "1": "encoded_string_2" +} +``` + +Optional fields for production bot checks: + +```json +{ + "event_token": "hash_from_cleantalk_js", + "0": "encoded_string" +} +``` + +### Response format + +```json +{ + "success": true, + "data": [ + { + "is_allowed": true, + "show_comment": false, + "comment": "Allowed", + "encoded_email": "...", + "decoded_email": "user@example.com" + } + ] +} +``` + +## How decoding works + +``` +User click on encoded contact + → contacts_encoder.js (fetch decode endpoint) + → runDecoding() + → checkRequest() → Cleantalk::checkBot() (event_type: CONTACT_DECODING) + → JSON response + → popup with decoded contact ``` + +If the CleanTalk API returns a connection error, decoding is still allowed and the error is returned in `comment`. + +## Troubleshooting + +| Problem | Likely cause | +|---------|----------------| +| Email is blurred but click does nothing | `ContactsEncoder` created inside `DOMContentLoaded` — remove the wrapper | +| Decode returns empty / error | Wrong `api_key`, or JSON body format mismatch | +| `checkBot` always allows | API connection error — library allows decode on API failure | +| Click on text around email ignored | Only `` is clickable | + +## Development + +```bash +composer install +composer test +``` + +## Links + +- [contacts-encoder on GitHub](https://github.com/CleanTalk/contacts-encoder) +- [cleantalk/antispam on Packagist](https://packagist.org/packages/cleantalk/antispam) +- [CleanTalk](https://cleantalk.org/) diff --git a/lib/Cleantalk/Common/ContactsEncoder/assets/images/demo-page.png b/lib/Cleantalk/Common/ContactsEncoder/assets/images/demo-page.png new file mode 100644 index 000000000..929f41eaa Binary files /dev/null and b/lib/Cleantalk/Common/ContactsEncoder/assets/images/demo-page.png differ diff --git a/lib/Cleantalk/Common/ContactsEncoder/composer.json b/lib/Cleantalk/Common/ContactsEncoder/composer.json index da06fa4d5..750521bc4 100644 --- a/lib/Cleantalk/Common/ContactsEncoder/composer.json +++ b/lib/Cleantalk/Common/ContactsEncoder/composer.json @@ -1,6 +1,23 @@ { "name": "cleantalk/contacts-encoder", - "description": "CleanTalk ContactsEncoder class", + "description": "Email obfuscation for email addresses and phone numbers. Stops smart bots via the CleanTalk anti-spam cloud. Works with any framework or plain HTML.", + "homepage": "https://cleantalk.org/contact-encoder", + "keywords": [ + "email-obfuscation", + "email-protection", + "anti-spam", + "spam-protection", + "bot-protection", + "phone-number", + "contact-form", + "privacy", + "gdpr", + "mailto" + ], + "support": { + "issues": "https://github.com/CleanTalk/contacts-encoder/issues", + "source": "https://github.com/CleanTalk/contacts-encoder" + }, "authors": [ { "name": "CleanTalk Team", @@ -8,6 +25,9 @@ } ], "license": "GPL-3.0-or-later", + "require": { + "cleantalk/antispam": "^1.6" + }, "require-dev": { "vimeo/psalm": "^4.8", "phpunit/phpunit": "^8.5.52", @@ -25,7 +45,8 @@ }, "config": { "allow-plugins": { - "dealerdirect/phpcodesniffer-composer-installer": true + "dealerdirect/phpcodesniffer-composer-installer": true, + "cleantalk/apbct-installer": false } }, "autoload": { diff --git a/lib/Cleantalk/Common/Helper.php b/lib/Cleantalk/Common/Helper.php index 79e07925d..993f2c858 100644 --- a/lib/Cleantalk/Common/Helper.php +++ b/lib/Cleantalk/Common/Helper.php @@ -98,11 +98,11 @@ public static function ipGet($ip_type_to_get = 'real', $v4_only = true, $headers ? explode(',', $source) : (array)$source; if ( isset($tmp[0]) ) { - $ip_version = self::ipValidate(trim($tmp[0])); + $ip_version = self::ipValidate(trim($tmp[0], " \n\r\t\v\x00")); if ($ip_version) { $out = $ip_version === 'v6' && ! $v4_only - ? self::ipV6Normalize(trim($tmp[0])) - : trim($tmp[0]); + ? self::ipV6Normalize(trim($tmp[0], " \n\r\t\v\x00")) + : trim($tmp[0], " \n\r\t\v\x00"); } } } @@ -241,8 +241,8 @@ public static function ipGet($ip_type_to_get = 'real', $v4_only = true, $headers case 'x_forwarded_for': $headers = $headers ?: self::httpGetHeaders(); if (isset($headers['X-Forwarded-For'])) { - $tmp = explode(',', trim($headers['X-Forwarded-For'])); - $tmp = trim($tmp[0]); + $tmp = explode(',', trim($headers['X-Forwarded-For'], " \n\r\t\v\x00")); + $tmp = trim($tmp[0], " \n\r\t\v\x00"); $ip_version = self::ipValidate($tmp); if ($ip_version) { $out = $ip_version === 'v6' && ! $v4_only ? self::ipV6Normalize($tmp) : $tmp; @@ -254,8 +254,8 @@ public static function ipGet($ip_type_to_get = 'real', $v4_only = true, $headers case 'x_real_ip': $headers = $headers ?: self::httpGetHeaders(); if (isset($headers['X-Real-Ip'])) { - $tmp = explode(",", trim($headers['X-Real-Ip'])); - $tmp = trim($tmp[0]); + $tmp = explode(",", trim($headers['X-Real-Ip'], " \n\r\t\v\x00")); + $tmp = trim($tmp[0], " \n\r\t\v\x00"); $ip_version = self::ipValidate($tmp); if ($ip_version) { $out = $ip_version === 'v6' && ! $v4_only ? self::ipV6Normalize($tmp) : $tmp; @@ -489,7 +489,7 @@ public static function cidrValidate($cidr) */ public static function ipV6Normalize($ip) { - $ip = trim($ip); + $ip = trim($ip, " \n\r\t\v\x00"); // Searching for ::ffff:xx.xx.xx.xx patterns and turn it to IPv6 if (preg_match('/^::ffff:([0-9]{1,3}\.?){4}$/', $ip)) { $ip = dechex((int)sprintf("%u", ip2long(substr($ip, 7)))); @@ -590,21 +590,47 @@ public static function ipResolve($ip) } /** - * Resolve DNS to IP + * Resolve DNS to IP. * - * @param $host - * @param bool $out + * $host must be a full URL that passes FILTER_VALIDATE_URL (scheme required). + * A bare hostname such as HTTP_HOST, or any non-string value, is rejected + * and $out is returned. * - * @return bool + * @param mixed $host Full URL (FILTER_VALIDATE_URL); other types are rejected + * @param bool|string $out Fallback when $host is invalid or lookup fails + * + * @return bool|string First A-record IPv4 on success, otherwise $out * @psalm-suppress PossiblyUnusedMethod */ public static function dnsResolve($host, $out = false) { // Check if the $url is set and it is an url - if ( ! $host || ! filter_var($host, FILTER_VALIDATE_URL)) { + if ( ! is_string($host) || $host === '' || ! filter_var($host, FILTER_VALIDATE_URL)) { return $out; } + if ( strpos($host, '://') !== false ) { + $parsed_host = parse_url($host, PHP_URL_HOST); + if ( is_string($parsed_host) && $parsed_host !== '' ) { + $host = $parsed_host; + } + } + + if ( strpos($host, ':') !== false && ! filter_var($host, FILTER_VALIDATE_IP) ) { + $host = strstr($host, ':', true); + } + + $is_ip = filter_var($host, FILTER_VALIDATE_IP); + + if ( ! filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) + && ! $is_ip ) { + return false; + } + + if ( $is_ip ) { + return $host; + } + // Get DNS records about URL if (function_exists('dns_get_record')) { $records = dns_get_record($host, DNS_A); @@ -903,7 +929,9 @@ public static function getMimeType($data, $type = '') } elseif (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $type = finfo_buffer($finfo, $data); - finfo_close($finfo); + if (PHP_VERSION_ID < 80000) { + finfo_close($finfo); + } } // @ToDo the method must return comparison result: return $type === mime_content_type($data) @@ -914,7 +942,7 @@ public static function bufferTrimAndClearFromEmptyLines($buffer) { $buffer = (array)$buffer; foreach ($buffer as $indx => &$line) { - $line = trim($line); + $line = trim($line, " \n\r\t\v\x00"); if ($line === '') { unset($buffer[$indx]); } @@ -982,7 +1010,7 @@ public static function bufferCsvGetMap(&$csv) */ public static function bufferCsvPopLineToArray(&$csv, $map = array()) { - $line = trim(static::bufferCsvPopLine($csv)); + $line = trim(static::bufferCsvPopLine($csv), " \n\r\t\v\x00"); $line = strpos($line, '\'') === 0 ? str_getcsv($line, ',', '\'', "\0") : explode(',', $line); diff --git a/lib/Cleantalk/Common/TextPlate.php b/lib/Cleantalk/Common/TextPlate.php index 970bafe3a..59cfc1bcd 100644 --- a/lib/Cleantalk/Common/TextPlate.php +++ b/lib/Cleantalk/Common/TextPlate.php @@ -33,7 +33,7 @@ public static function textPlateRender(string $_text, array $_plate, bool $trim { try { $search = []; - $_text = $trim ? trim($_text) : $_text; + $_text = $trim ? trim($_text, " \n\r\t\v\x00") : $_text; foreach ($_plate as $key => $value) { $key = self::validatePlateKey($key, $_text); $value = self::validatePlateValue($value, $key); diff --git a/readme.txt b/readme.txt index 25054a23b..4058e8175 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Tags: antispam, honeypot, bot, captcha, spam Requires at least: 4.7 Tested up to: 7.1 Requires PHP: 7.2 -Stable tag: 6.87 +Stable tag: 6.88 License: GPLv2 Top-rated antispam for contact forms, comments, WooCommerce, eCommerce, and login. No CAPTCHAs, no friction, just background anti spam protection. @@ -426,6 +426,35 @@ CleanTalk stops up to 99.998% of spam bots, so you can disable other anti-spam p == Changelog == += 6.88 16.09.2026 = +New. ContactEncoder. Add option to exclude selected contact data. +New. Code. IMetric service. Integrations performance metrics. +New. BotDetectorService. Frontend data log. +New. Code. Integrations performance base metrics. +Upd.Code. frontend_data logger. +Upd. BotDetectorService. FD log updates. +Upd. IMetricDTOTrait. Now integration metrics can be disabled via const APBCT_SERVICE__DISABLE_INTEGRATION_METRICS. +Upd. Settings. On wpms improve warnings appears. +Upd. Frontend Data log. AltSession transport implemented. +Upd. Code. Make patterns for case-insensitivity and improve helper methods. +Upd. Integrations. Improve ajax prefilter. +Upd. ContactEncoder. Imrove area-label processing. +Upd. ContactEncoder. Improve shortcode flow. +Mod. Banners. Editing texts in trial and renew banners +Fix. ContactEncoder. Unfreeze composer version. +Fix. RemoteCalls. Edits by update_settings. +Fix. SFW. Clearing SFW Outdated errors when updating by cron or in manual mode +Fix. AltSession. Editing in rest alt session endpoint +Fix. Moderate url fixed. +Fix. RemoteCalls. Edits by update_settings +Fix. ContactEncoder. Shortcode edits +Fix. AltSession. Editing in rest alt session endpoint +Fix. Alt cookies. Validation apbct_antiflood_passed fixed. +Fix. Imetric. Cast to int float values. +Fix. Cookie. Renaming the wordpress_apbct_antibot cookie +Fix. Code. Fixed compatibility with php8.5. +Fix. TRP. Editing styles. + = 6.87 02.09.2026 = Fix. Integrations. Improve statement to attaching assets on login page. Fix. ContactEncoder. Improve compatibility with WP Grid Builder. diff --git a/tests/Antispam/IntegrationMetrics/IMetricDTOTest.php b/tests/Antispam/IntegrationMetrics/IMetricDTOTest.php new file mode 100644 index 000000000..7562809ec --- /dev/null +++ b/tests/Antispam/IntegrationMetrics/IMetricDTOTest.php @@ -0,0 +1,87 @@ +assertSame('unset', $dto->integration_name); + $this->assertSame('1.0.0', $dto->dto_version); + $this->assertSame(0, $dto->peak_memory_diff_kb); + $this->assertSame(0, $dto->total_exec_time_ms); + $this->assertSame(array(), $dto->custom_fields); + $this->assertSame(array(), $dto->spans); + $this->assertSame(array(), $dto->variable_peak_kb); + $this->assertSame(0, $dto->timer_on_start_msec); + $this->assertSame(0, $dto->memory_usage_on_start_kb); + $this->assertSame(0, $dto->peak_memory_on_start_kb); + $this->assertFalse($dto->is_released); + } + + public function testSenderInfoKey() + { + $this->assertSame('imetric', IMetricDTO::$SENDER_INFO_KEY); + } + + public function testGetArrayContainsPublishedProperties() + { + $dto = new IMetricDTO(); + $dto->integration_name = 'MyIntegration'; + $dto->dto_version = '2.5.7'; + $dto->peak_memory_diff_kb = 10.5; + $dto->total_exec_time_ms = 123.4; + $dto->custom_fields = array('foo' => 'bar'); + $dto->spans = array('span1' => array('time_msec' => 1)); + $dto->variable_peak_kb = array('span1' => 2.2); + + $array = $dto->getArray(); + + $this->assertArrayHasKey('integration_name', $array); + $this->assertArrayHasKey('dto_version', $array); + $this->assertArrayHasKey('peak_memory_diff_kb', $array); + $this->assertArrayHasKey('total_exec_time_ms', $array); + $this->assertArrayHasKey('custom_fields', $array); + $this->assertArrayHasKey('spans', $array); + $this->assertArrayHasKey('variable_peak_kb', $array); + + $this->assertSame('MyIntegration', $array['integration_name']); + $this->assertSame('2.5.7', $array['dto_version']); + $this->assertSame(10.5, $array['peak_memory_diff_kb']); + $this->assertSame(123.4, $array['total_exec_time_ms']); + $this->assertSame(array('foo' => 'bar'), $array['custom_fields']); + } + + public function testGetArraySkipsInternalProperties() + { + $dto = new IMetricDTO(); + $dto->is_released = true; + $dto->peak_memory_on_start_kb = 999; + $dto->memory_usage_on_start_kb = 888; + $dto->timer_on_start_msec = 777; + + $array = $dto->getArray(); + + $this->assertArrayNotHasKey('is_released', $array); + $this->assertArrayNotHasKey('peak_memory_on_start_kb', $array); + $this->assertArrayNotHasKey('memory_usage_on_start_kb', $array); + $this->assertArrayNotHasKey('timer_on_start_msec', $array); + $this->assertArrayNotHasKey('SENDER_INFO_KEY', $array); + } + + public function testGetJSONMatchesArray() + { + $dto = new IMetricDTO(); + $dto->integration_name = 'Foo'; + $dto->custom_fields = array('a' => 1, 'b' => 'two'); + + $json = $dto->getJSON(); + + $this->assertIsString($json); + $decoded = json_decode($json, true); + $this->assertSame($dto->getArray(), $decoded); + } +} diff --git a/tests/Antispam/IntegrationMetrics/IMetricDTOTraitTest.php b/tests/Antispam/IntegrationMetrics/IMetricDTOTraitTest.php new file mode 100644 index 000000000..7a98aecaa --- /dev/null +++ b/tests/Antispam/IntegrationMetrics/IMetricDTOTraitTest.php @@ -0,0 +1,97 @@ +assertNull($fixture->getIMetricDTO()); + $this->assertNull($fixture->imetric_dto_version); + } + + public function testSetIMetricDTOStoresInstance() + { + $fixture = new IMetricDTOTraitFixture(); + $dto = new IMetricDTO(); + + $fixture->setIMetricDTO($dto); + + $this->assertSame($dto, $fixture->getIMetricDTO()); + } + + public function testSetIMetricDTOKeepsDefaultVersionWhenNoOverride() + { + $fixture = new IMetricDTOTraitFixture(); + $dto = new IMetricDTO(); + $original_version = $dto->dto_version; + + $fixture->setIMetricDTO($dto); + + $this->assertSame($original_version, $fixture->getIMetricDTO()->dto_version); + } + + public function testSetIMetricDTOOverridesVersionWhenSet() + { + $fixture = new IMetricDTOTraitFixture(); + $fixture->imetric_dto_version = '3.1.4'; + $dto = new IMetricDTO(); + + $fixture->setIMetricDTO($dto); + + $this->assertSame('3.1.4', $fixture->getIMetricDTO()->dto_version); + $this->assertSame('3.1.4', $dto->dto_version); + } + + public function testGetIMetricDTOReturnsNullWhenDisabled() + { + // Создаем mock объекта с трейтом + $fixture = $this->getMockBuilder(IMetricDTOTraitFixture::class) + ->onlyMethods(['imetricIsDisabled']) + ->getMock(); + + // Настраиваем mock: метод imetricIsDisabled() должен вернуть true + $fixture->expects($this->once()) + ->method('imetricIsDisabled') + ->willReturn(true); + + // Устанавливаем DTO + $dto = new IMetricDTO(); + $fixture->setIMetricDTO($dto); + + // Проверяем, что getIMetricDTO() возвращает null, несмотря на установленный DTO + $this->assertNull($fixture->getIMetricDTO()); + + // Проверяем, что свойство imetric_dto_version осталось null (как в оригинальном тесте) + $this->assertNull($fixture->imetric_dto_version); + } + + public function testGetIMetricDTOReturnsDtoWhenEnabled() + { + // Создаем mock с переопределенным методом imetricIsDisabled() + $fixture = $this->getMockBuilder(IMetricDTOTraitFixture::class) + ->onlyMethods(['imetricIsDisabled']) + ->getMock(); + + // Метод возвращает false (метрики включены) + $fixture->expects($this->once()) + ->method('imetricIsDisabled') + ->willReturn(false); + + $dto = new IMetricDTO(); + $fixture->setIMetricDTO($dto); + + // Проверяем, что getIMetricDTO() возвращает DTO + $this->assertSame($dto, $fixture->getIMetricDTO()); + } +} diff --git a/tests/Antispam/IntegrationMetrics/IMetricServiceTest.php b/tests/Antispam/IntegrationMetrics/IMetricServiceTest.php new file mode 100644 index 000000000..da0b01b13 --- /dev/null +++ b/tests/Antispam/IntegrationMetrics/IMetricServiceTest.php @@ -0,0 +1,324 @@ +imetric_dto; + } + } +} + +class IMetricServiceTest extends TestCase +{ + public function testGetDTOReturnsFalseWhenVersionNotSet() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + $this->assertFalse(IMetricService::getDTO($integration)); + } + + public function testGetDTOReturnsFalseForNonIntegration() + { + $integration = new IMetricServiceNonIntegrationFixture(); + $this->assertFalse(IMetricService::getDTO($integration)); + } + + public function testGetDTOReturnsPopulatedDTO() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + $integration->imetric_dto_version = '9.9.9'; + + $dto = IMetricService::getDTO($integration); + + $this->assertInstanceOf(IMetricDTO::class, $dto); + $this->assertSame('9.9.9', $dto->dto_version); + $this->assertSame('IMetricServiceIntegrationBaseFixture', $dto->integration_name); + $this->assertGreaterThan(0, $dto->timer_on_start_msec); + $this->assertGreaterThanOrEqual(0, $dto->memory_usage_on_start_kb); + $this->assertGreaterThanOrEqual(0, $dto->peak_memory_on_start_kb); + $this->assertFalse($dto->is_released); + } + + public function testGetDTOWorksForIntegrationByClassBase() + { + $integration = new IMetricServiceIntegrationByClassBaseFixture(); + $integration->imetric_dto_version = '1.2.3'; + + $dto = IMetricService::getDTO($integration); + + $this->assertInstanceOf(IMetricDTO::class, $dto); + $this->assertSame('1.2.3', $dto->dto_version); + $this->assertSame('IMetricServiceIntegrationByClassBaseFixture', $dto->integration_name); + } + + public function testSeekCreatesSpan() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + $dto = new IMetricDTO(); + $integration->setIMetricDTO($dto); + + IMetricService::seek($integration, 'my_span'); + + $this->assertArrayHasKey('my_span', $dto->spans); + $span = $dto->spans['my_span']; + $this->assertFalse($span['released']); + $this->assertArrayHasKey('time_msec', $span); + $this->assertArrayHasKey('memory_kb', $span); + $this->assertArrayHasKey('memory_peak_kb', $span); + } + + public function testSeekIsNoOpForNonIntegration() + { + $integration = new IMetricServiceNonIntegrationFixture(); + $dto = new IMetricDTO(); + $integration->imetric_dto = $dto; + + IMetricService::seek($integration, 'my_span'); + + $this->assertSame(array(), $dto->spans); + } + + public function testSeekIsNoOpWhenDTOReleased() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + $dto = new IMetricDTO(); + $dto->is_released = true; + $integration->setIMetricDTO($dto); + + IMetricService::seek($integration, 'my_span'); + + $this->assertSame(array(), $dto->spans); + } + + public function testSeekIsNoOpWhenDTOMissing() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + + IMetricService::seek($integration, 'my_span'); + + $this->assertNull($integration->getIMetricDTO()); + } + + public function testSeekDoesNotOverwriteExistingSpan() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + $dto = new IMetricDTO(); + $integration->setIMetricDTO($dto); + + IMetricService::seek($integration, 'my_span'); + $original = $dto->spans['my_span']; + usleep(1000); + IMetricService::seek($integration, 'my_span'); + + $this->assertSame($original, $dto->spans['my_span']); + } + + public function testLeaseMarksSpanReleased() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + $dto = new IMetricDTO(); + $integration->setIMetricDTO($dto); + + IMetricService::seek($integration, 'my_span'); + usleep(1000); + IMetricService::lease($integration, 'my_span'); + + $this->assertTrue($dto->spans['my_span']['released']); + $this->assertGreaterThanOrEqual(0, $dto->spans['my_span']['time_msec']); + } + + public function testLeaseIsNoOpForNonIntegration() + { + $integration = new IMetricServiceNonIntegrationFixture(); + $dto = new IMetricDTO(); + $dto->spans = array('my_span' => array( + 'time_msec' => 1.0, + 'memory_kb' => 1.0, + 'memory_peak_kb' => 1.0, + 'released' => false, + )); + $integration->imetric_dto = $dto; + + IMetricService::lease($integration, 'my_span'); + + $this->assertFalse($dto->spans['my_span']['released']); + } + + public function testReleaseAllSpansReleasesEverySpan() + { + $dto = new IMetricDTO(); + $dto->spans = array( + 'a' => array('time_msec' => 1.0, 'memory_kb' => 1.0, 'memory_peak_kb' => 1.0, 'released' => false), + 'b' => array('time_msec' => 2.0, 'memory_kb' => 2.0, 'memory_peak_kb' => 2.0, 'released' => false), + ); + + IMetricService::releaseAllSpans($dto); + + $this->assertTrue($dto->spans['a']['released']); + $this->assertTrue($dto->spans['b']['released']); + } + + public function testReleaseAllSpansSkipsAlreadyReleased() + { + $dto = new IMetricDTO(); + $dto->spans = array( + 'a' => array('time_msec' => 5.0, 'memory_kb' => 5.0, 'memory_peak_kb' => 5.0, 'released' => true), + ); + + IMetricService::releaseAllSpans($dto); + + $this->assertSame(5.0, $dto->spans['a']['time_msec']); + $this->assertTrue($dto->spans['a']['released']); + } + + public function testFinalizeDTOReleasesAndReturnsJSON() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + $integration->imetric_dto_version = '1.0.0'; + $dto = IMetricService::getDTO($integration); + $integration->setIMetricDTO($dto); + IMetricService::seek($integration, 'span_a'); + usleep(500); + + $json = IMetricService::finalizeDTO($integration); + + $this->assertIsString($json); + $decoded = json_decode($json, true); + $this->assertIsArray($decoded); + $this->assertTrue($dto->is_released); + $this->assertArrayHasKey('span_a', $decoded['spans']); + $this->assertTrue($decoded['spans']['span_a']['released']); + $this->assertGreaterThanOrEqual(0, $decoded['total_exec_time_ms']); + } + + public function testFinalizeDTOReturnsDefaultWhenDTOMissing() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + + $json = IMetricService::finalizeDTO($integration); + + $this->assertIsString($json); + $decoded = json_decode($json, true); + $this->assertIsArray($decoded); + $this->assertSame('unset', $decoded['integration_name']); + } + + public function testFinalizeDTOReturnsDefaultWhenDTOAlreadyReleased() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + $dto = new IMetricDTO(); + $dto->is_released = true; + $integration->setIMetricDTO($dto); + + $json = IMetricService::finalizeDTO($integration); + + $decoded = json_decode($json, true); + $this->assertSame('unset', $decoded['integration_name']); + } + + public function testSetCustomFieldStoresValue() + { + $dto = new IMetricDTO(); + + IMetricService::setCustomField($dto, 'foo', 'bar'); + + $this->assertSame('bar', $dto->custom_fields['foo']); + } + + public function testSetCustomFieldIsNoOpOnReleasedDTO() + { + $dto = new IMetricDTO(); + $dto->is_released = true; + + IMetricService::setCustomField($dto, 'foo', 'bar'); + + $this->assertArrayNotHasKey('foo', $dto->custom_fields); + } + + public function testSetCustomFieldIsNoOpWhenDTONull() + { + IMetricService::setCustomField(null, 'foo', 'bar'); + $this->assertTrue(true); + } + + public function testDumpVarsSizeStoresMaxSerializedSize() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + $dto = new IMetricDTO(); + $integration->setIMetricDTO($dto); + $small = 'x'; + $large = str_repeat('y', 2048); + + IMetricService::dumpVarsSize($integration, array('small' => $small, 'large' => $large), 'vars_span'); + + $this->assertArrayHasKey('vars_span', $dto->variable_peak_kb); + $expected_kb = round(strlen(serialize($large)) / 1024, 1); + $this->assertSame($expected_kb, $dto->variable_peak_kb['vars_span']); + } + + public function testDumpVarsSizeIsNoOpWhenVarsEmpty() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + $dto = new IMetricDTO(); + $integration->setIMetricDTO($dto); + + IMetricService::dumpVarsSize($integration, array(), 'vars_span'); + + $this->assertSame(array(), $dto->variable_peak_kb); + } + + public function testDumpVarsSizeIsNoOpWhenDTOMissing() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + + IMetricService::dumpVarsSize($integration, array('a' => 'b'), 'vars_span'); + + $this->assertNull($integration->getIMetricDTO()); + } + + public function testDumpVarsSizeUsesDefaultSpanName() + { + $integration = new IMetricServiceIntegrationBaseFixture(); + $dto = new IMetricDTO(); + $integration->setIMetricDTO($dto); + + IMetricService::dumpVarsSize($integration, array('a' => 'value')); + + $this->assertArrayHasKey('undefined_variable_span', $dto->variable_peak_kb); + } +} diff --git a/tests/Antispam/IntegrationsByHook/TestNinjaForms.php b/tests/Antispam/IntegrationsByHook/TestNinjaForms.php index 4249fe5e5..1b2b536db 100644 --- a/tests/Antispam/IntegrationsByHook/TestNinjaForms.php +++ b/tests/Antispam/IntegrationsByHook/TestNinjaForms.php @@ -7,7 +7,6 @@ use Cleantalk\ApbctWP\State; use Cleantalk\ApbctWP\Variables\Post; use PHPUnit\Framework\TestCase; -use Mockery\MockInterface; class TestNinjaForms extends TestCase { @@ -16,9 +15,6 @@ class TestNinjaForms extends TestCase /** @var NinjaForms */ private $ninjaForms; - /** @var MockInterface */ - private $mockGlobalApbct; - protected function setUp(): void { parent::setUp(); diff --git a/tests/ApbctWP/ContactsEncoder/Exclusions/TestExclusionsService.php b/tests/ApbctWP/ContactsEncoder/Exclusions/TestExclusionsService.php index a48357a8a..2c16d61ab 100644 --- a/tests/ApbctWP/ContactsEncoder/Exclusions/TestExclusionsService.php +++ b/tests/ApbctWP/ContactsEncoder/Exclusions/TestExclusionsService.php @@ -651,6 +651,58 @@ public function testByContentSignsIgnoresNonArrayFilterResult() $this->assertFalse($result); } + public function testIsContactExcludedMatchesEmailAndPhoneVariants() + { + $params = new Params(); + $params->api_key = 'testapikey'; + $params->excluded_strings = array('keep@example.com', '+1 800 555-1234', 'company.org'); + $service = new ExclusionsService($params); + + $this->assertTrue($service->isContactExcluded('keep@example.com')); + $this->assertTrue($service->isContactExcluded('mailto:keep@example.com')); + $this->assertTrue($service->isContactExcluded('office@company.org')); + $this->assertTrue($service->isContactExcluded('(800) 555-1234')); + $this->assertFalse($service->isContactExcluded('public@other.net')); + $this->assertFalse($service->isContactExcluded('(800) 555-9999')); + } + + public function testIsContactExcludedDoesNotCrossMatchEmailAndPhoneDigits() + { + $params = new Params(); + $params->api_key = 'testapikey'; + $params->excluded_strings = array('+1 800 555-1234', 'user12345678@example.com'); + $service = new ExclusionsService($params); + + $this->assertFalse($service->isContactExcluded('ticket18005551234@shop.com')); + $this->assertFalse($service->isContactExcluded('123-456-7890')); + $this->assertTrue($service->isContactExcluded('(800) 555-1234')); + $this->assertTrue($service->isContactExcluded('user12345678@example.com')); + } + + public function testParseExcludedStringsSplitsLines() + { + $parsed = \Cleantalk\Common\ContactsEncoder\Exclusions\ExclusionsService::parseExcludedStrings( + "keep@example.com\n+1 800 555-1234\nexample.com\n" + ); + + $this->assertSame( + array('keep@example.com', '+1 800 555-1234', 'example.com'), + $parsed + ); + } + + public function testParseExcludedStringsKeepsCommaInsideALine() + { + $parsed = \Cleantalk\Common\ContactsEncoder\Exclusions\ExclusionsService::parseExcludedStrings( + "keep@example.com, office@example.com\n+1 800 555-1234" + ); + + $this->assertSame( + array('keep@example.com, office@example.com', '+1 800 555-1234'), + $parsed + ); + } + /** * Helper method to invoke private methods for testing * diff --git a/tests/ApbctWP/ContactsEncoder/Integrations/TestCEIntegrationCommentList.php b/tests/ApbctWP/ContactsEncoder/Integrations/TestCEIntegrationCommentList.php deleted file mode 100644 index 8f950da90..000000000 --- a/tests/ApbctWP/ContactsEncoder/Integrations/TestCEIntegrationCommentList.php +++ /dev/null @@ -1,63 +0,0 @@ -' - . '
    ' - . '
  1. [apbct_encode_data]
  2. ' - . '
  3. Second comment text
  4. ' - . '
  5. [apbct_encode_data]z[/apbct_encode_data][/apbct_encode_data]
  6. ' - . '
' - . '
'; - - $integration = new CEIntegrationCommentList(); - $protected = $integration->protect($html); - $restored = $integration->restore($protected); - - $this->assertStringNotContainsString('[apbct_encode_data]', $protected); - $this->assertStringContainsString('%%APBCT_COMMENT_REGION_0%%', $protected); - $this->assertSame($html, $restored); - } - - public function testProtectStandaloneCommentListWithoutCommentsWrapper() - { - $html = '
    ' - . '
  1. one
  2. ' - . '
  3. two
  4. ' - . '
'; - - $integration = new CEIntegrationCommentList(); - $protected = $integration->protect($html); - - $this->assertStringContainsString('%%APBCT_COMMENT_REGION_0%%', $protected); - $this->assertSame($html, $integration->restore($protected)); - } - - public function testProtectLeavesContentWithoutCommentListUntouched() - { - $html = '
[apbct_encode_data]post@example.com[/apbct_encode_data]
'; - - $integration = new CEIntegrationCommentList(); - - $this->assertSame($html, $integration->protect($html)); - } - - public function testRestoreClearsPlaceholdersForSubsequentCalls() - { - $html = '
  1. one
'; - - $integration = new CEIntegrationCommentList(); - $protected = $integration->protect($html); - $restored = $integration->restore($protected); - - $this->assertSame($html, $restored); - $this->assertSame($protected, $integration->restore($protected)); - } -} diff --git a/tests/ApbctWP/ContactsEncoder/Shortcodes/ExcludedEncodeContentSCTest.php b/tests/ApbctWP/ContactsEncoder/Shortcodes/ExcludedEncodeContentSCTest.php index b809daa54..8c8bc8c66 100644 --- a/tests/ApbctWP/ContactsEncoder/Shortcodes/ExcludedEncodeContentSCTest.php +++ b/tests/ApbctWP/ContactsEncoder/Shortcodes/ExcludedEncodeContentSCTest.php @@ -453,4 +453,14 @@ public function testFilterTheTitleAcceptsSingleArgument(): void $result = $this->exclude_content_sc->filterTheTitle($title); $this->assertSame($title, $result); } + + public function testChangeContentBeforeEncoderModifySkipsShortcodeWithHtmlTags(): void + { + $content = '[apbct_skip_encoding]

safe@example.com

[/apbct_skip_encoding]'; + + $result = $this->exclude_content_sc->changeContentBeforeEncoderModify($content); + + $this->assertSame($content, $result); + $this->assertCount(0, $this->exclude_content_sc->shortcode_replacements); + } } diff --git a/tests/ApbctWP/ContactsEncoder/TestContactsEncoder.php b/tests/ApbctWP/ContactsEncoder/TestContactsEncoder.php index b108360a6..b767ed4b8 100644 --- a/tests/ApbctWP/ContactsEncoder/TestContactsEncoder.php +++ b/tests/ApbctWP/ContactsEncoder/TestContactsEncoder.php @@ -42,7 +42,9 @@ private function clearDecoderPassedCookie(): void while ($ref) { if ($ref->hasProperty('variables')) { $prop = $ref->getProperty('variables'); - $prop->setAccessible(true); + if ( PHP_VERSION_ID < 80100 ) { + $prop->setAccessible(true); + } $variables = $prop->getValue($cookie_instance); unset($variables[$cookie_name]); $prop->setValue($cookie_instance, $variables); @@ -222,6 +224,143 @@ public function testModifyContentSkipsEmailsInsideOptionTags() $this->assertStringContainsString('apbct-email-encoder', $result); } + /** + * Settings skip list keeps listed emails plain, including in title-like strings. + */ + public function testModifyContentSkipsEmailsFromExcludedStringsSetting() + { + global $apbct; + $previous = isset($apbct->settings['data__email_decoder_excluded_strings']) + ? $apbct->settings['data__email_decoder_excluded_strings'] + : ''; + + $keep = 'keep@example.com'; + $encode = 'public@other.net'; + $title = 'Contact ' . $keep . ' or ' . $encode; + + $apbct->settings['data__email_decoder_excluded_strings'] = $keep; + $this->contacts_encoder->dropInstance(); + $this->contacts_encoder = apbctGetContactsEncoder(); + + $result = $this->contacts_encoder->modifyContent($title); + + $apbct->settings['data__email_decoder_excluded_strings'] = $previous; + $this->contacts_encoder->dropInstance(); + $this->contacts_encoder = apbctGetContactsEncoder(); + + $this->assertStringContainsString($keep, $result); + $this->assertStringNotContainsString($encode, $result); + $this->assertStringContainsString('apbct-email-encoder', $result); + } + + /** + * Domain fragment in the skip list excludes every matching email. + */ + public function testModifyContentSkipsEmailsByDomainFragment() + { + global $apbct; + $previous = isset($apbct->settings['data__email_decoder_excluded_strings']) + ? $apbct->settings['data__email_decoder_excluded_strings'] + : ''; + + $skip = 'office@company.org'; + $encode = 'user@other.net'; + + $apbct->settings['data__email_decoder_excluded_strings'] = 'company.org'; + $this->contacts_encoder->dropInstance(); + $this->contacts_encoder = apbctGetContactsEncoder(); + + $result = $this->contacts_encoder->modifyContent($skip . ' ' . $encode); + + $apbct->settings['data__email_decoder_excluded_strings'] = $previous; + $this->contacts_encoder->dropInstance(); + $this->contacts_encoder = apbctGetContactsEncoder(); + + $this->assertStringContainsString($skip, $result); + $this->assertStringNotContainsString($encode, $result); + $this->assertStringContainsString('apbct-email-encoder', $result); + } + + /** + * Phone skip list matches format variants by digits. + */ + public function testModifyContentSkipsPhonesFromExcludedStringsSetting() + { + global $apbct; + $previous_strings = isset($apbct->settings['data__email_decoder_excluded_strings']) + ? $apbct->settings['data__email_decoder_excluded_strings'] + : ''; + $previous_phones = $apbct->settings['data__email_decoder_encode_phone_numbers']; + + $keep = '(800) 555-1234'; + $encode = '(800) 555-9999'; + + $apbct->settings['data__email_decoder_encode_phone_numbers'] = 1; + $apbct->settings['data__email_decoder_excluded_strings'] = '+1 800 555-1234'; + $this->contacts_encoder->dropInstance(); + $this->contacts_encoder = apbctGetContactsEncoder(); + + $result = $this->contacts_encoder->modifyContent('Call ' . $keep . ' or ' . $encode); + + $apbct->settings['data__email_decoder_excluded_strings'] = $previous_strings; + $apbct->settings['data__email_decoder_encode_phone_numbers'] = $previous_phones; + $this->contacts_encoder->dropInstance(); + $this->contacts_encoder = apbctGetContactsEncoder(); + + $this->assertStringContainsString($keep, $result); + $this->assertStringNotContainsString($encode, $result); + $this->assertStringContainsString('apbct-email-encoder', $result); + } + + /** + * aria-label values must survive email encoding round-trip intact. + */ + public function testModifyContentPreservesAriaLabelWithEmail() + { + $email = 'info@example.com'; + $content = ''; + + $result = $this->contacts_encoder->modifyContent($content); + + $this->assertStringContainsString('aria-label="Contact us at ' . $email . '"', $result); + $this->assertStringNotContainsString('%%APBCT_ARIA_', $result); + $this->assertStringNotContainsString('ct_temp_aria_', $result); + } + + /** + * CVE-2026-77830: planted ct_temp_aria_0 must not be rewritten during aria-label restore. + */ + public function testModifyContentDoesNotRestorePlantedCtTempAriaToken() + { + $payload = '
test
' + . 'ct_temp_aria_0' + . 'test'; + + $result = $this->contacts_encoder->modifyContent($payload); + + $this->assertStringContainsString('ct_temp_aria_0', $result); + $this->assertNotRegExp('/>\s*aria-label\s*=/', $result); + } + + /** + * CVE-2026-77830: Wordfence PoC must not produce aria-label markup breakout after encoding. + */ + public function testModifyContentWordfenceAriaLabelXssPayloadDoesNotBreakOut() + { + $payload = '
test
' . "\n" + . 'ct_temp_aria_0' + . 'test'; + + $result = $this->contacts_encoder->modifyContent($payload); + + $planted_token_preserved = strpos($result, 'ct_temp_aria_0') !== false; + $breakout_injected = (bool) preg_match('/>\s*aria-label\s*=/', $result); + + $this->assertTrue($planted_token_preserved, 'Planted ct_temp_aria_0 token must survive encoder round-trip.'); + $this->assertFalse($breakout_injected, 'Encoder must not inject aria-label markup via token substitution.'); + } + public function testEncodingPhoneNumbers() { global $apbct; @@ -316,6 +455,22 @@ public function testGetPhonesEncodingLongDescription() $this->assertStringEndsWith('>', $description); } + public function testGetExcludedStringsDescription() + { + $description = ContactsEncoder::getExcludedStringsDescription(); + $this->assertIsString($description); + $this->assertNotEmpty($description); + + $long = ContactsEncoder::getExcludedStringsLongDescription(); + $this->assertIsString($long); + $this->assertStringContainsString('128 characters', $long); + $this->assertStringContainsString('one value per line', $description); + $this->assertStringNotContainsString('comma', strtolower($description)); + $this->assertStringNotContainsString('comma', strtolower($long)); + $this->assertStringNotContainsString('apbct_skip_encoding', $description); + $this->assertStringNotContainsString('apbct_skip_encoding', $long); + } + public function testModifyBuffer() { global $apbct; diff --git a/tests/ApbctWP/ContactsEncoder/TestContactsEncoderShortCodeEncode.php b/tests/ApbctWP/ContactsEncoder/TestContactsEncoderShortCodeEncode.php index dfa5a44f5..e0435a63c 100644 --- a/tests/ApbctWP/ContactsEncoder/TestContactsEncoderShortCodeEncode.php +++ b/tests/ApbctWP/ContactsEncoder/TestContactsEncoderShortCodeEncode.php @@ -102,8 +102,8 @@ public function testChangeContentBeforeEncoderModifyReplacesShortcodesWithPlaceh $content = 'Some content with [apbct_encode_data]Test content[/apbct_encode_data]'; $result = $this->shortcode->changeContentBeforeEncoderModify($content); - $this->assertStringContainsString('%%APBCT_SHORT_CODE_INCLUDE_EE_0%%', $result); - $this->assertArrayHasKey('%%APBCT_SHORT_CODE_INCLUDE_EE_0%%', $this->shortcode->shortcode_replacements); + $this->assertRegExp('/%%APBCT_SHORT_CODE_INCLUDE_EE_0_[a-z0-9]{32}%%/', $result); + $this->assertCount(1, $this->shortcode->shortcode_replacements); } public function testChangeContentBeforeEncoderModifyUsesPlaceholdersWhenDecoderCookieSet() @@ -113,8 +113,8 @@ public function testChangeContentBeforeEncoderModifyUsesPlaceholdersWhenDecoderC $content = 'Some content with [apbct_encode_data]Test content[/apbct_encode_data]'; $result = $this->shortcode->changeContentBeforeEncoderModify($content); - $this->assertStringContainsString('%%APBCT_SHORT_CODE_INCLUDE_EE_0%%', $result); - $this->assertArrayHasKey('%%APBCT_SHORT_CODE_INCLUDE_EE_0%%', $this->shortcode->shortcode_replacements); + $this->assertRegExp('/%%APBCT_SHORT_CODE_INCLUDE_EE_0_[a-z0-9]{32}%%/', $result); + $this->assertCount(1, $this->shortcode->shortcode_replacements); } public function testChangeContentBeforeEncoderModifyUsesPlaceholdersWhenGlobalEmailEncodingDisabled() @@ -128,7 +128,7 @@ public function testChangeContentBeforeEncoderModifyUsesPlaceholdersWhenGlobalEm $content = '

[apbct_encode_data]Test content[/apbct_encode_data]

'; $result = $shortcode->changeContentBeforeEncoderModify($content); - $this->assertStringContainsString('%%APBCT_SHORT_CODE_INCLUDE_EE_0%%', $result); + $this->assertRegExp('/%%APBCT_SHORT_CODE_INCLUDE_EE_0_[a-z0-9]{32}%%/', $result); $this->assertStringContainsString('

', $result); } @@ -174,8 +174,8 @@ public function testShortcodeOutsideHtmlIsProcessed() $result = $this->shortcode->changeContentBeforeEncoderModify($content); - $this->assertStringContainsString( - '%%APBCT_SHORT_CODE_INCLUDE_EE_0%%', + $this->assertRegExp( + '/%%APBCT_SHORT_CODE_INCLUDE_EE_0_[a-z0-9]{32}%%/', $result ); @@ -191,8 +191,10 @@ public function testMultipleShortcodesAreHandled() $result = $this->shortcode->changeContentBeforeEncoderModify($content); - $this->assertStringContainsString('%%APBCT_SHORT_CODE_INCLUDE_EE_0%%', $result); - $this->assertStringContainsString('%%APBCT_SHORT_CODE_INCLUDE_EE_1%%', $result); + // both placeholders in the same render pass must share the same nonce + preg_match('/%%APBCT_SHORT_CODE_INCLUDE_EE_0_([a-z0-9]{32})%%/', $result, $matches); + $this->assertNotEmpty($matches); + $this->assertStringContainsString('%%APBCT_SHORT_CODE_INCLUDE_EE_1_' . $matches[1] . '%%', $result); } public function testHtmlAttributeBreakPayloadDoesNotExplode() @@ -234,8 +236,8 @@ public function testShortcodeWithAttributesIsProcessed() $result = $this->shortcode->changeContentBeforeEncoderModify($content); - $this->assertStringContainsString( - '%%APBCT_SHORT_CODE_INCLUDE_EE_0%%', + $this->assertRegExp( + '/%%APBCT_SHORT_CODE_INCLUDE_EE_0_[a-z0-9]{32}%%/', $result ); @@ -271,7 +273,7 @@ public function testPlaceholderNeverAppearsInsideHtmlAttribute() $result = $this->shortcode->changeContentBeforeEncoderModify($content); - $this->assertStringNotContainsString('%%APBCT_SHORT_CODE_INCLUDE_EE_0%%', $result); + $this->assertNotRegExp('/%%APBCT_SHORT_CODE_INCLUDE_EE_0(_[a-z0-9]{32})?%%/', $result); } public function testCallbackEscapesReplacingText() @@ -357,6 +359,7 @@ public function testBufferModeDoesNotAbsorbCommentsFromEncodeDataTags() global $apbct; $previous_buffer_setting = $apbct->settings['data__email_decoder_buffer']; + $previous_buffer = $apbct->buffer; $apbct->settings['data__email_decoder_buffer'] = true; $html = '

    ' @@ -375,6 +378,83 @@ public function testBufferModeDoesNotAbsorbCommentsFromEncodeDataTags() $this->assertStringNotContainsString('apbct-email-encoder', $buffer); } finally { $apbct->settings['data__email_decoder_buffer'] = $previous_buffer_setting; + $apbct->buffer = $previous_buffer; + } + } + + public function testBufferModeDoesNotAbsorbBlockThemeCommentsFromEncodeDataTags() + { + global $apbct; + + $previous_buffer_setting = $apbct->settings['data__email_decoder_buffer']; + $previous_buffer = $apbct->buffer; + $apbct->settings['data__email_decoder_buffer'] = true; + + $html = '
      ' + . '
    1. [apbct_encode_data]
    2. ' + . '
    3. Keep this block comment
    4. ' + . '
    5. [apbct_encode_data]z[/apbct_encode_data][/apbct_encode_data]
    6. ' + . '
    '; + + try { + $buffer = $this->shortcodes_service->modifyBufferBefore($html); + $buffer = apbctGetContactsEncoder()->modifyContent($buffer); + $buffer = $this->shortcodes_service->modifyBufferAfter($buffer); + + $this->assertStringContainsString('Keep this block comment', $buffer); + $this->assertStringContainsString('[apbct_encode_data]', $buffer); + $this->assertStringNotContainsString('apbct-email-encoder', $buffer); + } finally { + $apbct->settings['data__email_decoder_buffer'] = $previous_buffer_setting; + $apbct->buffer = $previous_buffer; + } + } + + public function testShortcodeWithHtmlTagsIsNotExtracted() + { + $content = '[apbct_encode_data]

    Keep this paragraph

    [/apbct_encode_data]'; + + $result = $this->shortcode->changeContentBeforeEncoderModify($content); + + $this->assertSame($content, $result); + $this->assertCount(0, $this->shortcode->shortcode_replacements); + } + + public function testShortcodeWithPlainTextIsStillExtracted() + { + $content = "[apbct_encode_data]\nuser@example.com\n[/apbct_encode_data]"; + + $result = $this->shortcode->changeContentBeforeEncoderModify($content); + + $this->assertRegExp('/%%APBCT_SHORT_CODE_INCLUDE_EE_0_[a-z0-9]{32}%%/', $result); + $this->assertCount(1, $this->shortcode->shortcode_replacements); + } + + public function testBufferModeDoesNotAbsorbArbitraryHtmlBetweenEncodeDataTags() + { + global $apbct; + + $previous_buffer_setting = $apbct->settings['data__email_decoder_buffer']; + $previous_buffer = $apbct->buffer; + $apbct->settings['data__email_decoder_buffer'] = true; + + $html = '
    ' + . '

    [apbct_encode_data]

    ' + . '

    Keep this article paragraph

    ' + . '

    [/apbct_encode_data]

    ' + . '
    '; + + try { + $buffer = $this->shortcodes_service->modifyBufferBefore($html); + $buffer = apbctGetContactsEncoder()->modifyContent($buffer); + $buffer = $this->shortcodes_service->modifyBufferAfter($buffer); + + $this->assertStringContainsString('Keep this article paragraph', $buffer); + $this->assertStringContainsString('[apbct_encode_data]', $buffer); + $this->assertStringNotContainsString('apbct-email-encoder', $buffer); + } finally { + $apbct->settings['data__email_decoder_buffer'] = $previous_buffer_setting; + $apbct->buffer = $previous_buffer; } } diff --git a/tests/ApbctWP/TestBotDetectorService.php b/tests/ApbctWP/TestBotDetectorService.php new file mode 100644 index 000000000..45f3fcfec --- /dev/null +++ b/tests/ApbctWP/TestBotDetectorService.php @@ -0,0 +1,350 @@ +data['cookies_type'] = 'alternative'; + $apbct->data['bot_detector_enabled'] = '1'; + $apbct->settings['exclusions__bot_detector'] = 0; + $apbct->settings['exclusions__bot_detector__form_attributes'] = ''; + $apbct->settings['exclusions__bot_detector__form_children_attributes'] = ''; + $apbct->settings['exclusions__bot_detector__form_parent_attributes'] = ''; + $this->resetTransports(); + } + + protected function tearDown(): void + { + $this->resetTransports(); + } + + /** + * Every transport keeps its own state between calls: + * Post caches each variable in the singleton, NoCookie holds a static array, + * AltSessions store the values in the DB. Without the full reset the tests + * would depend on the execution order. + */ + private function resetTransports() + { + $_POST = array(); + Post::getInstance()->variables = array(); + NoCookie::$no_cookies_data = array(); + } + + private function makeRawBrowserState($log = '[["success"],[true]]') + { + return json_encode(array( + 'frontend_data_log' => $log, + 'botd_logic_loaded' => 1, + 'botd_wrapper_loaded' => 1, + )); + } + + private function assertSuccessfulLogResult($json) + { + $result = json_decode($json, true); + $this->assertSame('OK', $result['plugin_status']); + $this->assertSame('', $result['error_msg']); + $this->assertSame(array(array('success'), array(true)), $result['apbct_browser_state']['frontend_data_log']); + $this->assertSame(1, $result['apbct_browser_state']['botd_logic_loaded']); + $this->assertSame(1, $result['apbct_browser_state']['botd_wrapper_loaded']); + } + + // ------------------------------------------------------------------ + // getWrapperUrl() + // ------------------------------------------------------------------ + + public function test_getWrapperUrl_returnsNonEmptyString() + { + $url = BotDetectorService::getWrapperUrl(); + $this->assertEquals('https://fd.cleantalk.org/ct-bot-detector-wrapper.js', $url); + } + + // ------------------------------------------------------------------ + // getBrowserState() — pure function, no globals involved + // ------------------------------------------------------------------ + + public function test_getBrowserState_returnsEmptyWhenNoSources() + { + $this->assertSame(array(), BotDetectorService::getBrowserState(array())); + } + + public function test_getBrowserState_returnsEmptyWhenAllSourcesEmpty() + { + $this->assertSame(array(), BotDetectorService::getBrowserState(array( + 'request_parameters' => '', + 'post_browser_state' => null, + 'post_data' => array(), + ))); + } + + public function test_getBrowserState_parsesJsonFromRequestParameters() + { + $raw = json_encode(array( + 'frontend_data_log' => '[["success"],[true]]', + 'botd_logic_loaded' => 1, + 'botd_wrapper_loaded' => 1, + )); + + $state = BotDetectorService::getBrowserState(array( + 'request_parameters' => $raw, + )); + + $this->assertSame(array(array('success'), array(true)), $state['frontend_data_log']); + $this->assertSame(1, $state['botd_logic_loaded']); + $this->assertSame(1, $state['botd_wrapper_loaded']); + } + + public function test_getBrowserState_requestParametersWinsOverPost() + { + $winner = json_encode(array('botd_wrapper_loaded' => 1)); + $loser = json_encode(array('botd_wrapper_loaded' => 0)); + + $state = BotDetectorService::getBrowserState(array( + 'request_parameters' => $winner, + 'post_browser_state' => $loser, + 'post_data' => array('apbct_browser_state' => $loser), + )); + + $this->assertSame(1, $state['botd_wrapper_loaded']); + } + + public function test_getBrowserState_fallsBackToPostBrowserState() + { + $raw = json_encode(array('botd_logic_loaded' => 1)); + + $state = BotDetectorService::getBrowserState(array( + 'request_parameters' => '', + 'post_browser_state' => $raw, + )); + + $this->assertSame(1, $state['botd_logic_loaded']); + } + + public function test_getBrowserState_fallsBackToPostDataArray() + { + $raw = json_encode(array('botd_wrapper_loaded' => 1)); + + $state = BotDetectorService::getBrowserState(array( + 'post_data' => array('apbct_browser_state' => $raw), + )); + + $this->assertSame(1, $state['botd_wrapper_loaded']); + } + + public function test_getBrowserState_acceptsArraySource() + { + $state = BotDetectorService::getBrowserState(array( + 'request_parameters' => array( + 'frontend_data_log' => array(array('success')), + 'botd_logic_loaded' => 1, + 'botd_wrapper_loaded' => 1, + ), + )); + + $this->assertSame(array(array('success')), $state['frontend_data_log']); + $this->assertSame(1, $state['botd_logic_loaded']); + $this->assertSame(1, $state['botd_wrapper_loaded']); + } + + public function test_getBrowserState_handlesEscapedJson() + { + $raw = addslashes(json_encode(array( + 'frontend_data_log' => '[["ok"]]', + 'botd_logic_loaded' => 1, + 'botd_wrapper_loaded' => 1, + ))); + + $state = BotDetectorService::getBrowserState(array( + 'request_parameters' => $raw, + )); + + $this->assertSame(array(array('ok')), $state['frontend_data_log']); + $this->assertSame(1, $state['botd_logic_loaded']); + $this->assertSame('request_parameters', $state['log_source']); + } + + public function test_getBrowserState_returnsEmptyOnInvalidJson() + { + $this->assertSame(array(), BotDetectorService::getBrowserState(array( + 'request_parameters' => 'not a json', + ))); + } + + public function test_getBrowserState_partialStateIsFilledWithDefaults() + { + $state = BotDetectorService::getBrowserState(array( + 'request_parameters' => json_encode(array('botd_wrapper_loaded' => 1)), + )); + + $this->assertSame(array(), $state['frontend_data_log']); + $this->assertSame(0, $state['botd_logic_loaded']); + $this->assertSame(1, $state['botd_wrapper_loaded']); + } + + public function test_getBrowserState_frontendDataLogAsInvalidStringBecomesEmptyArray() + { + $state = BotDetectorService::getBrowserState(array( + 'request_parameters' => json_encode(array( + 'frontend_data_log' => 'not-a-json', + 'botd_logic_loaded' => 1, + 'botd_wrapper_loaded' => 1, + )), + )); + + $this->assertSame(array(), $state['frontend_data_log']); + } + + public function test_getBrowserState_ignoresPostDataWithoutBrowserStateKey() + { + $state = BotDetectorService::getBrowserState(array( + 'post_data' => array('something_else' => 'value'), + )); + + $this->assertSame(array(), $state); + } + + // ------------------------------------------------------------------ + // getCustomExclusionsFromStateSettings() + // ------------------------------------------------------------------ + + public function test_getCustomExclusions_returnsEmptyWhenFeatureDisabled() + { + global $apbct; + $apbct->settings['exclusions__bot_detector'] = 0; + $apbct->settings['exclusions__bot_detector__form_attributes'] = 'foo'; + + $this->assertSame(array(), BotDetectorService::getCustomExclusionsFromStateSettings()); + } + + public function test_getCustomExclusions_returnsEmptyWhenAllSignsAreEmpty() + { + global $apbct; + $apbct->settings['exclusions__bot_detector'] = 1; + + $this->assertSame(array(), BotDetectorService::getCustomExclusionsFromStateSettings()); + } + + public function test_getCustomExclusions_buildsExclusionsFromFormAttributes() + { + global $apbct; + $apbct->settings['exclusions__bot_detector'] = 1; + $apbct->settings['exclusions__bot_detector__form_attributes'] = 'foo,bar'; + + $exclusions = BotDetectorService::getCustomExclusionsFromStateSettings(); + + $this->assertCount(2, $exclusions); + $this->assertSame('exclusion_0', $exclusions[0]['exclusion_id']); + $this->assertSame('foo', $exclusions[0]['signs_to_check']['form_attributes']); + $this->assertSame('', $exclusions[0]['signs_to_check']['form_children_attributes']); + $this->assertSame('', $exclusions[0]['signs_to_check']['form_parent_attributes']); + $this->assertSame('exclusion_1', $exclusions[1]['exclusion_id']); + $this->assertSame('bar', $exclusions[1]['signs_to_check']['form_attributes']); + } + + public function test_getCustomExclusions_buildsAcrossAllSignTypes() + { + global $apbct; + $apbct->settings['exclusions__bot_detector'] = 1; + $apbct->settings['exclusions__bot_detector__form_attributes'] = 'a'; + $apbct->settings['exclusions__bot_detector__form_children_attributes'] = 'b'; + $apbct->settings['exclusions__bot_detector__form_parent_attributes'] = 'c'; + + $exclusions = BotDetectorService::getCustomExclusionsFromStateSettings(); + + $this->assertCount(3, $exclusions); + $this->assertSame('a', $exclusions[0]['signs_to_check']['form_attributes']); + $this->assertSame('b', $exclusions[1]['signs_to_check']['form_children_attributes']); + $this->assertSame('c', $exclusions[2]['signs_to_check']['form_parent_attributes']); + } + + // ------------------------------------------------------------------ + // getPreparedExclusions() + // ------------------------------------------------------------------ + + public function test_getPreparedExclusions_returnsEmptyJsonArrayWhenNothingConfigured() + { + $this->assertSame('[]', BotDetectorService::getPreparedExclusions()); + } + + public function test_getPreparedExclusions_returnsValidExclusionsAsJson() + { + global $apbct; + $apbct->settings['exclusions__bot_detector'] = 1; + $apbct->settings['exclusions__bot_detector__form_attributes'] = 'foo'; + + $json = BotDetectorService::getPreparedExclusions(); + $decoded = json_decode($json, true); + + $this->assertIsArray($decoded); + $this->assertCount(1, $decoded); + $this->assertSame('exclusion_0', $decoded[0]['exclusion_id']); + $this->assertSame('foo', $decoded[0]['signs_to_check']['form_attributes']); + } + + // ------------------------------------------------------------------ + // getFrontendDataLog() — integration over real transports + // ------------------------------------------------------------------ + + public function test_getFrontendDataLog_readsFromNoCookie() + { + global $apbct; + $apbct->data['cookies_type'] = 'none'; + NoCookie::set('apbct_browser_state', $this->makeRawBrowserState()); + + $this->assertSuccessfulLogResult(BotDetectorService::getFrontendDataLog()); + + $result = json_decode(BotDetectorService::getFrontendDataLog(), true); + $this->assertSame('request_parameters', $result['apbct_browser_state']['log_source']); + } + + public function test_getFrontendDataLog_readsFromPost() + { + $_POST['apbct_browser_state'] = $this->makeRawBrowserState(); + + $this->assertSuccessfulLogResult(BotDetectorService::getFrontendDataLog()); + + $result = json_decode(BotDetectorService::getFrontendDataLog(), true); + $this->assertSame('post_browser_state', $result['apbct_browser_state']['log_source']); + } + + public function test_getFrontendDataLog_readsFromPostDataArray() + { + $_POST['data'] = array('apbct_browser_state' => $this->makeRawBrowserState()); + + $this->assertSuccessfulLogResult(BotDetectorService::getFrontendDataLog()); + + $result = json_decode(BotDetectorService::getFrontendDataLog(), true); + $this->assertSame('post_data', $result['apbct_browser_state']['log_source']); + } + + public function test_getFrontendDataLog_returnsErrorWhenDisabled() + { + global $apbct; + $apbct->data['bot_detector_enabled'] = '0'; + + $result = json_decode(BotDetectorService::getFrontendDataLog(), true); + + $this->assertSame('ERROR', $result['plugin_status']); + $this->assertSame('bot detector library usage is disabled', $result['error_msg']); + } + + public function test_getFrontendDataLog_returnsErrorWhenNoStateProvided() + { + $result = json_decode(BotDetectorService::getFrontendDataLog(), true); + + $this->assertSame('ERROR', $result['plugin_status']); + $this->assertSame('no browser state provided by the transport', $result['error_msg']); + } +} diff --git a/tests/ApbctWP/TestRemoteCalls.php b/tests/ApbctWP/TestRemoteCalls.php index d821e179e..3a1c499eb 100644 --- a/tests/ApbctWP/TestRemoteCalls.php +++ b/tests/ApbctWP/TestRemoteCalls.php @@ -361,6 +361,138 @@ public function itOnlyAllowsSfwUpdateWorkerForDelay() $this->assertEquals(['sfw_update__worker'], $allowedActions); } + /** @test */ + public function itAllowsDelayOnlyForWhitelistedAction() + { + $method = new ReflectionMethod(RemoteCalls::class, 'getDelayForAction'); + $method->setAccessible(true); + + $this->assertSame(5, $method->invoke(null, 'sfw_update__worker', 5)); + + $this->assertNull($method->invoke(null, 'sfw_update', 5)); + $this->assertNull($method->invoke(null, 'debug', 5)); + $this->assertNull($method->invoke(null, 'get_fresh_wpnonce', 5)); + $this->assertNull($method->invoke(null, 'post_api_key', 5)); + $this->assertNull($method->invoke(null, 'install_plugin', 5)); + $this->assertNull($method->invoke(null, '', 5)); + } + + /** @test */ + public function itIgnoresActionCaseWhenCheckingDelayPermission() + { + $method = new ReflectionMethod(RemoteCalls::class, 'getDelayForAction'); + $method->setAccessible(true); + + $this->assertSame(5, $method->invoke(null, 'SFW_UPDATE__WORKER', 5)); + $this->assertSame(5, $method->invoke(null, 'Sfw_Update__Worker', 5)); + } + + /** @test */ + public function itDoesNotAllowDelayForPrefixedActionName() + { + // perform() must pass the raw action name, not the one prefixed with 'action__' + $method = new ReflectionMethod(RemoteCalls::class, 'getDelayForAction'); + $method->setAccessible(true); + + $this->assertNull($method->invoke(null, 'action__sfw_update__worker', 5)); + } + + /** @test */ + public function itReturnsNullWhenDelayParamIsEmpty() + { + // No delay param — the action must be performed right here, not passed to the host + $method = new ReflectionMethod(RemoteCalls::class, 'getDelayForAction'); + $method->setAccessible(true); + + $this->assertNull($method->invoke(null, 'sfw_update__worker', null)); + $this->assertNull($method->invoke(null, 'sfw_update__worker', false)); + $this->assertNull($method->invoke(null, 'sfw_update__worker', '')); + $this->assertNull($method->invoke(null, 'sfw_update__worker', '0')); + $this->assertNull($method->invoke(null, 'sfw_update__worker', 0)); + } + + /** @test */ + public function itKeepsAllowedDelayValueAsIs() + { + $method = new ReflectionMethod(RemoteCalls::class, 'getDelayForAction'); + $method->setAccessible(true); + + $this->assertSame(1, $method->invoke(null, 'sfw_update__worker', 1)); + $this->assertSame(3, $method->invoke(null, 'sfw_update__worker', 3)); + $this->assertSame( + RemoteCalls::MAX_DELAY, + $method->invoke(null, 'sfw_update__worker', RemoteCalls::MAX_DELAY) + ); + } + + /** @test */ + public function itCapsDelayAtMaxDelay() + { + $method = new ReflectionMethod(RemoteCalls::class, 'getDelayForAction'); + $method->setAccessible(true); + + $this->assertSame( + RemoteCalls::MAX_DELAY, + $method->invoke(null, 'sfw_update__worker', RemoteCalls::MAX_DELAY + 1) + ); + $this->assertSame(RemoteCalls::MAX_DELAY, $method->invoke(null, 'sfw_update__worker', 999)); + $this->assertSame(RemoteCalls::MAX_DELAY, $method->invoke(null, 'sfw_update__worker', PHP_INT_MAX)); + } + + /** @test */ + public function itTurnsNegativeDelayIntoZeroButStillDelegatesToHost() + { + // Zero, not null: the call is still passed to the host, it just does not sleep + $method = new ReflectionMethod(RemoteCalls::class, 'getDelayForAction'); + $method->setAccessible(true); + + $this->assertSame(0, $method->invoke(null, 'sfw_update__worker', -1)); + $this->assertSame(0, $method->invoke(null, 'sfw_update__worker', -999)); + $this->assertSame(0, $method->invoke(null, 'sfw_update__worker', PHP_INT_MIN)); + } + + /** @test */ + public function itCastsNonIntegerDelayToInt() + { + $method = new ReflectionMethod(RemoteCalls::class, 'getDelayForAction'); + $method->setAccessible(true); + + $this->assertSame(7, $method->invoke(null, 'sfw_update__worker', '7')); + $this->assertSame(7, $method->invoke(null, 'sfw_update__worker', 7.9)); + $this->assertSame(0, $method->invoke(null, 'sfw_update__worker', 'abc')); + $this->assertSame(0, $method->invoke(null, 'sfw_update__worker', array(5))); + } + + /** @test */ + public function performDelegatesDelayDecisionToGetDelayForAction() + { + $method = new ReflectionMethod(RemoteCalls::class, 'perform'); + $source = implode('', array_slice( + file($method->getFileName()), + $method->getStartLine() - 1, + $method->getEndLine() - $method->getStartLine() + 1 + )); + + $this->assertStringContainsString( + "self::getDelayForAction(\$raw_action, Request::get('delay'))", + $source, + 'perform() must take the delay decision from getDelayForAction()' + ); + + // The branch is chosen by null, not by the value: a negative delay is still + // passed to the host instead of running the action locally + $this->assertStringContainsString( + 'if ( ! is_null($delay) ) {', + $source, + 'perform() must branch on null, not on the delay value' + ); + + $this->assertStringNotContainsString( + 'allowedActionsWithDelay', + $source, + 'The whitelist check belongs to getDelayForAction(), not to perform()' + ); + } // ========================================================================= // APBCT-W07: 'api_key' added to $sensitiveData list // ========================================================================= diff --git a/tests/ApbctWP/TestSubmitTimeHandler.php b/tests/ApbctWP/TestSubmitTimeHandler.php index 52c53ba7c..a9a1e51cf 100644 --- a/tests/ApbctWP/TestSubmitTimeHandler.php +++ b/tests/ApbctWP/TestSubmitTimeHandler.php @@ -64,9 +64,4 @@ public function testIsCalculationDisabledReturnsFalseWhenBotDetectorDisabled() $this->assertFalse($result); } - - protected function tearDown(): void - { - \Mockery::close(); - } } diff --git a/tests/Common/HelperTest.php b/tests/Common/HelperTest.php index 65b17355e..832f8f2fe 100644 --- a/tests/Common/HelperTest.php +++ b/tests/Common/HelperTest.php @@ -149,4 +149,15 @@ public function test_ipResolve_return_type() 'ipResolve should return false or a non-empty string hostname' ); } + + /** + * Detect MIME from a data buffer. Must not call deprecated finfo_close() on PHP 8.5+. + */ + public function test_getMimeType_from_buffer() + { + $type = Helper::getMimeType('hello', 'text/plain'); + + $this->assertIsString($type); + $this->assertNotSame('', $type); + } } diff --git a/tests/RootFile/TestAdminAntiBotCookie.php b/tests/RootFile/TestAdminAntiBotCookie.php index 826dc709d..e7dd04aaf 100644 --- a/tests/RootFile/TestAdminAntiBotCookie.php +++ b/tests/RootFile/TestAdminAntiBotCookie.php @@ -45,7 +45,7 @@ public function testAdminCookieIsNotRemoteCallToken() $antibot_hash = apbct_get_anti_bot_cookie_hash($apbct->api_key, $apbct->data['salt']); $rc_token = hash('sha256', $apbct->api_key . $apbct->data['salt']); - $this->assertStringContainsString('wordpress_apbct_antibot=', $output); + $this->assertStringContainsString('apbct_antibot=', $output); $this->assertStringContainsString($antibot_hash, $output); $this->assertStringNotContainsString( $rc_token, diff --git a/tests/RootFile/TestCheckValueSalt.php b/tests/RootFile/TestCheckValueSalt.php index e64d1be33..aa3c53e1d 100644 --- a/tests/RootFile/TestCheckValueSalt.php +++ b/tests/RootFile/TestCheckValueSalt.php @@ -49,18 +49,24 @@ public function testCheckValueWithSaltDiffersFromWithout() { global $apbct; - $with_salt = md5($apbct->api_key . $apbct->data['salt']); + $with_suffix = md5($apbct->api_key . $apbct->data['salt'] . '_apbct_cookies_test'); $without_salt = md5($apbct->api_key); + $rc_bearer = md5($apbct->api_key . $apbct->data['salt']); $this->assertNotEquals( $without_salt, - $with_salt, + $with_suffix, 'check_value must not equal md5(api_key) alone - salt must change the hash' ); + $this->assertNotEquals( + $rc_bearer, + $with_suffix, + 'check_value must not equal the RC bearer md5(api_key + salt) - purpose suffix must domain-separate it' + ); } /** - * Test that apbct_cookies_test() validates a cookie computed WITH salt. + * Test that apbct_cookies_test() validates a cookie computed WITH salt and purpose suffix. */ public function testApbctCookiesTestValidatesWithSalt() { @@ -68,7 +74,7 @@ public function testApbctCookiesTestValidatesWithSalt() $cookie_test_value = array( 'cookies_names' => array(), - 'check_value' => md5($apbct->api_key . $apbct->data['salt']), + 'check_value' => md5($apbct->api_key . $apbct->data['salt'] . '_apbct_cookies_test'), ); $cookie_prefix = function_exists('apbct__get_cookie_prefix') ? apbct__get_cookie_prefix() : ''; @@ -111,7 +117,7 @@ public function testApbctCookiesTestValidatesWithSaltAndTimestamp() $cookie_test_value = array( 'cookies_names' => array('ct_ps_timestamp'), - 'check_value' => md5($apbct->api_key . $apbct->data['salt'] . $timestamp), + 'check_value' => md5($apbct->api_key . $apbct->data['salt'] . '_apbct_cookies_test' . $timestamp), ); $cookie_prefix = function_exists('apbct__get_cookie_prefix') ? apbct__get_cookie_prefix() : ''; diff --git a/tests/StandaloneFunctions/SettingsTest.php b/tests/StandaloneFunctions/SettingsTest.php index c0d6392f0..b3f7f6b9f 100644 --- a/tests/StandaloneFunctions/SettingsTest.php +++ b/tests/StandaloneFunctions/SettingsTest.php @@ -122,6 +122,27 @@ public function test_apbct_settings__sanitize__exclusions__wrong_params() $this->assertIsString(apbct_settings__sanitize__exclusions('', 0)); } + public function test_apbct_settings__sanitize__excluded_contact_strings() + { + $this->assertSame('', apbct_settings__sanitize__excluded_contact_strings(null)); + $this->assertSame('', apbct_settings__sanitize__excluded_contact_strings('')); + $this->assertSame( + "keep@example.com\n+1 800 555-1234", + apbct_settings__sanitize__excluded_contact_strings("keep@example.com\n+1 800 555-1234\n") + ); + $this->assertSame( + 'keep@example.com, office@example.com', + apbct_settings__sanitize__excluded_contact_strings('keep@example.com, office@example.com') + ); + + $lines = array(); + for ( $i = 1; $i <= 25; $i++ ) { + $lines[] = 'user' . $i . '@example.com'; + } + $sanitized = apbct_settings__sanitize__excluded_contact_strings(implode("\n", $lines)); + $this->assertCount(20, explode("\n", $sanitized)); + } + public function test_apbct_settings__set_fields() { $fields = apbct_settings__set_fields(); @@ -151,4 +172,55 @@ public function test_apbct_settings__set_fields() $this->assertIsArray($fields[$key], "Key '{$key}' should be an array"); } } + + public function test_apbct_settings__clear_errors_current_site() + { + global $apbct; + + $apbct->errorAdd('sfw_outdated', 'SpamFireWall database is outdated.'); + $this->assertTrue($apbct->errorExists('sfw_outdated')); + + apbct_settings__clear_errors(false); + + $this->assertFalse($apbct->errorExists('sfw_outdated')); + $this->assertSame(array(), (array) $apbct->errors); + $this->assertSame(array(), get_option($apbct->option_prefix . '_errors')); + } + + public function test_apbct_settings__clear_errors_all_blogs_on_wpms() + { + global $apbct; + + if ( ! is_multisite() ) { + $this->markTestSkipped('Requires WordPress Multisite'); + } + + $option_name = $apbct->option_prefix . '_errors'; + $stale_error = array( + 'sfw_outdated' => array( + array( + 'error' => 'SpamFireWall database is outdated.', + 'error_time' => time(), + ), + ), + ); + + $apbct->errorAdd('sfw_outdated', 'SpamFireWall database is outdated.'); + + $blogs = get_sites(array('number' => 20)); + foreach ( $blogs as $blog ) { + update_blog_option((int) $blog->blog_id, $option_name, $stale_error); + } + + apbct_settings__clear_errors(true); + + $this->assertFalse($apbct->errorExists('sfw_outdated')); + foreach ( $blogs as $blog ) { + $this->assertSame( + array(), + get_blog_option((int) $blog->blog_id, $option_name), + 'Errors must be cleared on blog ' . $blog->blog_id + ); + } + } } diff --git a/tests/StandaloneFunctions/TestBotDetectorLogGathering.php b/tests/StandaloneFunctions/TestBotDetectorLogGathering.php deleted file mode 100644 index 133e0a9a3..000000000 --- a/tests/StandaloneFunctions/TestBotDetectorLogGathering.php +++ /dev/null @@ -1,89 +0,0 @@ -data['bot_detector_enabled'] = '1'; - AltSessions::set('ct_bot_detector_frontend_data_log', json_encode(['log' => 'data'])); - - $result = apbct__bot_detector_get_fd_log(); - $expected = json_encode([ - 'plugin_status' => 'OK', - 'error_msg' => '', - 'frontend_data_log' => ['log' => 'data'] - ]); - - $this->assertEquals($expected, $result); - } - - public function test_returnsErrorWhenDisabled() - { - global $apbct; - $apbct->data['bot_detector_enabled'] = '0'; - - $result = apbct__bot_detector_get_fd_log(); - $expected = json_encode([ - 'plugin_status' => 'ERROR', - 'error_msg' => 'bot detector library usage is disabled', - 'frontend_data_log' => '' - ]); - - $this->assertEquals($expected, $result); - } - - public function test_returnsErrorWhenNoLogFound() - { - global $apbct; - $apbct->data['bot_detector_enabled'] = '1'; - AltSessions::wipe(); - - $result = apbct__bot_detector_get_fd_log(); - $expected = json_encode([ - 'plugin_status' => 'ERROR', - 'error_msg' => 'no log found in alt sessions', - 'frontend_data_log' => '' - ]); - - $this->assertEquals($expected, $result); - } - - public function test_returnsErrorWhenLogNotString() - { - global $apbct; - $apbct->data['bot_detector_enabled'] = '1'; - AltSessions::set('ct_bot_detector_frontend_data_log', false); - - $result = apbct__bot_detector_get_fd_log(); - $expected = json_encode([ - 'plugin_status' => 'ERROR', - 'error_msg' => 'no log found in alt sessions', - 'frontend_data_log' => '' - ]); - - $this->assertEquals($expected, $result); - } - - public function test_returnsErrorWhenLogNotJson() - { - global $apbct; - $apbct->data['bot_detector_enabled'] = '1'; - AltSessions::set('ct_bot_detector_frontend_data_log', 'invalid json'); - - $result = apbct__bot_detector_get_fd_log(); - $expected = json_encode([ - 'plugin_status' => 'ERROR', - 'error_msg' => 'can not decode data from alt sessions', - 'frontend_data_log' => '' - ]); - - $this->assertEquals($expected, $result); - } -}