is_main_query() &&
$query->get('post_type') === 'abst_experiments'
) {
// Exclude completed tests from default view unless specifically filtered
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin list filtering; no state change.
if (!isset($_GET['post_status'])) {
$query->set('post_status', array('publish', 'draft', 'pending', 'private'));
}
// Author filtering for non-admin users
if (
apply_filters('abst_authors_see_own_posts', false) &&
!current_user_can('manage_options') &&
!current_user_can('edit_others_posts')
) {
$query->set('author', get_current_user_id());
}
}
}
/**
* Rename "All" to "Active Tests" and "Published" to "Running" in the post status views
* since the default view now excludes completed tests
*/
public function rename_all_to_active_tests($views) {
if (isset($views['all'])) {
$views['all'] = str_replace('All', 'Active Tests', $views['all']);
// Core counts every status under "All", but this view only lists these (see the
// pre_get_posts filter), so count the same statuses.
$counts = (array) wp_count_posts('abst_experiments', 'readable');
$active = 0;
foreach (array('publish', 'draft', 'pending', 'private') as $status) {
$active += isset($counts[$status]) ? (int) $counts[$status] : 0;
}
$views['all'] = preg_replace('/\([\d.,\s]+\)/', '(' . number_format_i18n($active) . ')', $views['all'], 1);
}
if (isset($views['publish'])) {
$views['publish'] = str_replace('Published', 'Running', $views['publish']);
}
return $views;
}
function add_split_test_params_to_bakery() {
// Fetch published abst_experiments for dropdown
vc_add_param('vc_row', array(
'type' => 'autocomplete',
'heading' => __('Choose a Test or Create a new test', 'ab-split-test-lite'),
'param_name' => 'test_id',
'description' => __('Choose an existing split test', 'ab-split-test-lite'),
'group' => __('Split Test Settings', 'ab-split-test-lite'),
));
vc_add_param('vc_row', array(
'type' => 'dropdown',
'heading' => __('Version', 'ab-split-test-lite'),
'param_name' => 'test_variation',
'value' => array_flip($this->onpage_variation_choices()),
'std' => 'original',
'description' => __('Tag this as the Original or the Variation.', 'ab-split-test-lite'),
'group' => __('Split Test Settings', 'ab-split-test-lite'),
));
//do the same for vc_section
vc_add_param('vc_section', array(
'type' => 'autocomplete',
'heading' => __('Choose a Test or Create a new test', 'ab-split-test-lite'),
'param_name' => 'test_id',
'description' => __('Choose an existing split test', 'ab-split-test-lite'),
'group' => __('Split Test Settings', 'ab-split-test-lite'),
));
vc_add_param('vc_section', array(
'type' => 'dropdown',
'heading' => __('Version', 'ab-split-test-lite'),
'param_name' => 'test_variation',
'value' => array_flip($this->onpage_variation_choices()),
'std' => 'original',
'description' => __('Tag this as the Original or the Variation.', 'ab-split-test-lite'),
'group' => __('Split Test Settings', 'ab-split-test-lite'),
));
}
// WP Bakery autocomplete callback for the Test ID field (on-page tests)
function bakery_autocomplete( $query, $tag, $param_name ) {
//if qiery is id
if(is_numeric($query))
{
$post = get_post($query);
if($post && $post->post_type == 'abst_experiments' && $post->post_status == 'publish')
{
return array(
'value' => $post->ID,
'label' => $post->ID . ' - ' . $post->post_title . ' [' . $post->post_name . ']',
);
}
}
$args = array(
'post_type' => 'abst_experiments',
'post_status' => 'publish',
'posts_per_page' => 10,
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Bounded admin selector query by plugin-owned meta.
'meta_query' => array(
array(
'key' => 'test_type',
'value' => 'ab_test',
),
),
's' => $query,
);
$posts = get_posts( $args );
$results = array();
foreach ( $posts as $post ) {
$results[] = array(
'value' => $post->ID,
'label' => $post->ID . ' - ' . $post->post_title . ' [' . $post->post_name . ']',
);
}
return $results;
}
function bakery_autocomplete_render( $value, $settings, $tag ) {
$post = get_post( $value['value'] ?? $value );
if ( $post && $post->post_type === 'abst_experiments' ) {
return array(
'value' => $post->ID,
'label' => $post->ID . ' - ' . $post->post_title . ' [' . $post->post_name . ']',
);
}
return $value;
}
function add_split_test_attributes_to_bakery($class_string, $tag, $atts = null) {
// Early return if no atts provided or not the right tag
if (!$atts || !is_array($atts) || !in_array($tag, ['vc_row', 'vc_section'])) {
return $class_string;
}
// WPBakery fills in the Version default on every row, so only a row with a test is tagged;
// an ab-var- class on its own would hide the row
if (empty($atts['test_id'])) {
return $class_string;
}
$class_string .= ' ab-'. sanitize_html_class($atts['test_id']);
$class_string .= ' ab-var-'. abst_normalize_onpage_variation($atts['test_variation'] ?? '', 'original');
return $class_string;
}
function activate_plugin($plugin) {
// Only after a single "Activate" click: never during bulk activation, WP-CLI or another plugin's activation.
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check; core verifies the nonce before activating.
$abst_activation_action = isset($_GET['action']) ? sanitize_key(wp_unslash($_GET['action'])) : '';
if($plugin == plugin_basename(ABST_LITE_MAIN_FILE) && 'activate' === $abst_activation_action && !(defined('WP_CLI') && WP_CLI)) {
if(is_plugin_active_for_network(ABST_PLUGIN_FOLDER.'/bt-bb-ab.php')) {
wp_safe_redirect(network_admin_url('admin.php?page=bt_bb_ab_test&wizard=1'));
} else {
wp_safe_redirect(admin_url('options-general.php?page=bt_bb_ab_test&wizard=1'));
}
exit;
}
}
function bt_ab_uninstall() {
abst_log('bt_ab_uninstall');
wp_clear_scheduled_hook('abst_plugin_version_check');
wp_clear_scheduled_hook('abst_refresh_conversion_pages_deferred');
wp_clear_scheduled_hook('abst_winner_check');
wp_clear_scheduled_hook('abst_delete_journey_data');
wp_clear_scheduled_hook('abst_trim_log');
}
/**
* Fires immediately after plugin update (automatic, manual, or remote)
* This catches updates that happen via WP Cron, MainWP, ManageWP, etc.
*
* @param WP_Upgrader $upgrader_object
* @param array $options
*/
function on_plugin_update($upgrader_object, $options) {
// Zip uploads (including "Replace current with uploaded") fire with
// action=install, never action=update, so handle both.
if (!isset($options['type']) || $options['type'] !== 'plugin') {
return;
}
$action = isset($options['action']) ? $options['action'] : '';
if ($action !== 'update' && $action !== 'install') {
return;
}
// Check if our plugin was updated
$our_plugin = plugin_basename(ABST_LITE_MAIN_FILE);
$ours = false;
if (isset($options['plugins'])) {
// Bulk update
foreach ((array) $options['plugins'] as $plugin) {
if ($plugin === $our_plugin) {
$ours = true;
break;
}
}
} elseif (isset($options['plugin']) && $options['plugin'] === $our_plugin) {
// Single plugin update
$ours = true;
} elseif ($action === 'install') {
// A zip install carries no plugin/plugins key, so identify the
// plugin from the upgrader itself.
if (is_object($upgrader_object) && is_callable(array($upgrader_object, 'plugin_info'))
&& $upgrader_object->plugin_info() === $our_plugin) {
$ours = true;
} elseif (is_object($upgrader_object) && isset($upgrader_object->result)
&& is_array($upgrader_object->result)
&& !empty($upgrader_object->result['destination_name'])
&& defined('ABST_PLUGIN_FOLDER')
&& $upgrader_object->result['destination_name'] === ABST_PLUGIN_FOLDER) {
$ours = true;
}
}
if ($ours) {
$this->clear_cache_on_update();
// upgrader_process_complete runs while the OLD code is still loaded,
// so re-check on cron shortly, once the new code is loaded.
$this->schedule_plugin_version_check();
}
}
/**
* Arm a one-off cron re-run of the version-change check shortly after an
* update/install completes.
*/
function schedule_plugin_version_check() {
if (!wp_next_scheduled('abst_plugin_version_check')) {
wp_schedule_single_event(time() + 30, 'abst_plugin_version_check');
}
}
/**
* Catch version changes missed by upgrader_process_complete, such as direct
* file replacement or deployment tools that do not run the WordPress updater.
* Called by the AB Split Test settings page loader.
*/
function maybe_handle_plugin_version_change() {
$stored_version = get_option('abst_plugin_version');
if ($stored_version === ABST_VERSION) {
return;
}
$this->clear_cache_on_update();
}
/**
* Clear cache and update version number on plugin update
* Uses existing comprehensive cache clearing function
*/
function clear_cache_on_update() {
$stored_version = get_option('abst_plugin_version');
$current_version = ABST_VERSION;
abst_log('Plugin updated from ' . ($stored_version ?: 'unknown') . ' to ' . $current_version . ' - clearing all caches if allowed');
$this->refresh_conversion_pages();
// Update the stored version
update_option('abst_plugin_version', $current_version, false);
abst_log('All caches cleared and version updated to ' . $current_version);
}
function save_idea_config($post_id, $data = array()) {
if (array_key_exists('abst_idea_hypothesis', $data) || array_key_exists('hypothesis', $data)) {
$idea_hypothesis = sanitize_textarea_field($data['abst_idea_hypothesis'] ?? $data['hypothesis'] ?? '');
update_post_meta($post_id, 'abst_idea_hypothesis', $idea_hypothesis);
}
if (array_key_exists('abst_idea_page_flow', $data) || array_key_exists('page', $data)) {
$idea_page_flow = sanitize_textarea_field($data['abst_idea_page_flow'] ?? $data['page'] ?? '');
update_post_meta($post_id, 'abst_idea_page_flow', $idea_page_flow);
}
if (array_key_exists('abst_idea_observed_problem', $data) || array_key_exists('problem', $data)) {
$idea_problem = sanitize_textarea_field($data['abst_idea_observed_problem'] ?? $data['problem'] ?? '');
update_post_meta($post_id, 'abst_idea_observed_problem', $idea_problem);
}
if (array_key_exists('abst_idea_next_step', $data) || array_key_exists('nextstep', $data)) {
$idea_next_step = sanitize_textarea_field($data['abst_idea_next_step'] ?? $data['nextstep'] ?? '');
update_post_meta($post_id, 'abst_idea_next_step', $idea_next_step);
}
foreach (['impact', 'reach', 'confidence', 'effort'] as $idea_score_key) {
$meta_key = 'abst_idea_' . $idea_score_key;
$has_value = array_key_exists($meta_key, $data) || array_key_exists($idea_score_key, $data);
if (!$has_value) {
continue;
}
$raw_value = $data[$meta_key] ?? $data[$idea_score_key] ?? '';
if ($raw_value === '' || $raw_value === null) {
delete_post_meta($post_id, $meta_key);
continue;
}
update_post_meta($post_id, $meta_key, max(1, min(5, intval($raw_value))));
}
}
function remove_bulk_actions( $actions, $post ){
if ( $post->post_type == "abst_experiments" ) {
unset( $actions['inline hide-if-no-js'] );
if( isset($actions['edit']) ) {
$actions['edit'] = str_replace("Edit","View",$actions['edit']);
}
}
return $actions;
}
function bt_include_ajax_url(){
if(!wp_doing_ajax()){
abst_add_inline_js(
'var bt_ajaxurl = ' . wp_json_encode( admin_url( 'admin-ajax.php' ) ) . ';'
. 'var bt_adminurl = ' . wp_json_encode( admin_url() ) . ';'
. 'var bt_pluginurl = ' . wp_json_encode( plugin_dir_url( __FILE__ ) ) . ';'
. 'var bt_homeurl = ' . wp_json_encode( home_url() ) . ';'
);
}
}
function bt_include_module()
{
$this->maybe_include_journey_module();
}
function maybe_include_journey_module() {
if(abst_get_admin_setting('abst_enable_user_journeys') == 1) {
include_once ( plugin_dir_path( __FILE__ ) . 'modules/journey.php');
}
}
function bt_include_support_module() {
include_once( plugin_dir_path( __FILE__ ) . 'modules/support/cache.php' );
include_once ( plugin_dir_path( __FILE__ ) . 'modules/support/support.php');
}
/**
* Hide admin bar when page is loaded inside heatmap iframe
*/
function hide_admin_bar_in_heatmap_iframe() {
//if logged in and can edit posts
if ( current_user_can('edit_posts') ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only display mode flag for the heatmap iframe.
if ( isset( $_GET['abst_heatmap_view'] ) && sanitize_text_field( wp_unslash( $_GET['abst_heatmap_view'] ) ) == '1' ) {
show_admin_bar( false );
}
}
}
// Resolves a post ID or slug to a post ID; 0 when no post matches.
function get_id_from_slug($slug) {
if((string) $slug === '')
return 0;
$post = false;
//if its an int then get the post from id
if(is_numeric($slug))
$post = get_post($slug);
//when its not a post id it should get by slug
if(empty($post))
$post = get_page_by_path($slug, OBJECT, 'any');
if(empty($post))
{
$post = get_posts(array
(
'name' => $slug,
'post_type' => 'any',
'posts_per_page' => 1
));
$post = $post[0] ?? false;
}
return empty($post) ? 0 : (int) $post->ID;
}
/**
* Store the two pages of a full page test: the original page (a page ID or an archive
* key) and the variation page ID (0 when none is chosen yet). A custom label names one
* page and the screenshot shows the variation page, so they are cleared when their
* page changes.
*
* @param int $test_id
* @param int|string $default_page
* @param int $variation_page
*/
function save_full_page_pages($test_id, $default_page, $variation_page) {
if (get_post_meta($test_id, 'test_type', true) === 'full_page') {
$previous_default_page = (string) get_post_meta($test_id, 'bt_experiments_full_page_default_page', true);
if ($previous_default_page !== '' && $previous_default_page !== (string) $default_page) {
delete_post_meta($test_id, 'original_label');
}
$previous_variation_page = absint(get_post_meta($test_id, 'variation_page', true));
if ($previous_variation_page && $previous_variation_page !== (int) $variation_page) {
delete_post_meta($test_id, 'variation_label');
delete_post_meta($test_id, 'variation_page_image');
}
}
update_post_meta($test_id, 'bt_experiments_full_page_default_page', $default_page);
if ($variation_page) {
update_post_meta($test_id, 'variation_page', (int) $variation_page);
} else {
delete_post_meta($test_id, 'variation_page');
}
}
/**
* The variation_page API parameter (a page ID or slug) as the page's ID.
*
* @param mixed $value
* @return int|WP_Error
*/
function resolve_variation_page_param($value) {
if (empty($value)) {
return new WP_Error('missing_variation_page', 'variation_page is required for full_page tests: the ID or slug of the variation page.', ['status' => 400, 'field' => 'variation_page']);
}
$page_id = is_scalar($value) ? $this->get_id_from_slug((string) $value) : 0;
if (!$page_id) {
return new WP_Error('invalid_variation_page', 'The variation page was not found. variation_page takes one page ID or slug.', ['status' => 400, 'field' => 'variation_page']);
}
return $page_id;
}
function save_test_config( $post_id, $data = array() ) {
require_once plugin_dir_path(__FILE__) . 'bt-bb-ab-validation.php';
$requested_status = sanitize_text_field((string) ($data['post_status'] ?? get_post_status($post_id)));
if($requested_status === 'abst_idea')
{
$this->save_idea_config($post_id, $data);
abst_log('Test #' . $post_id . ' saved (idea)');
return;
}
if(
isset($data['abst_idea_hypothesis']) ||
isset($data['abst_idea_page_flow']) ||
isset($data['abst_idea_observed_problem']) ||
isset($data['abst_idea_next_step']) ||
isset($data['abst_idea_impact']) ||
isset($data['abst_idea_reach']) ||
isset($data['abst_idea_confidence']) ||
isset($data['abst_idea_effort'])
) {
$this->save_idea_config($post_id, $data);
}
//test type
$is_first_save = get_post_meta( $post_id, 'test_type', true ) === ''; // no type yet: this save creates the test
$url_query = sanitize_text_field($data['test_type'] ?? ''); //ab_test full_page magic
update_post_meta( $post_id, 'test_type', $url_query );
//get json magic definition
// magic test
$magic_definition = $data['magic_definition'] ?? '';
if (!empty($magic_definition)) {
require_once plugin_dir_path(__FILE__) . 'bt-bb-ab-validation.php';
$decoded = json_decode($magic_definition, true);
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
// Normalize scope (sanitize and format)
$decoded = abst_prepare_magic_definition_for_write(abst_normalize_magic_definition($decoded));
// Validate magic definition including scope requirement
$validation_result = abst_validate_magic_definition($decoded);
if (is_wp_error($validation_result)) {
abst_log('ERROR: Magic definition validation failed: ' . $validation_result->get_error_message());
// Don't save invalid data - keep existing value
return $validation_result;
}
// Sanitize each element - but only for untrusted input
foreach ($decoded as $index => $element) {
if (isset($element['selector'])) {
$decoded[$index]['selector'] = sanitize_text_field($element['selector']);
}
if (isset($element['type'])) {
$decoded[$index]['type'] = sanitize_text_field($element['type']);
}
}
// Re-encode as JSON
$magic_definition = wp_json_encode($decoded, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} else {
// Don't overwrite a working test with malformed JSON.
abst_log('ERROR: magic_definition JSON decode failed. Existing value was preserved. Error: ' . json_last_error_msg());
return new WP_Error('invalid_magic_definition_json', 'The Magic definition is not valid JSON. The existing definition was kept.');
}
}
update_post_meta( $post_id, 'magic_definition', wp_slash( $magic_definition ) );
// Full page split test: the original page and the variation page.
// A page ID, or an archive key (category-news, post-type-archive-product) from the same list.
$default_page = sanitize_text_field( (string) ($data['bt_experiments_full_page_default_page'] ?? '') );
$default_page = is_numeric($default_page) ? absint($default_page) : $default_page;
$variation_page = isset($data['variation_page']) && is_scalar($data['variation_page']) ? $this->get_id_from_slug( sanitize_text_field( (string) $data['variation_page'] ) ) : 0;
$this->save_full_page_pages( $post_id, $default_page, $variation_page );
//url query
$url_query = sanitize_textarea_field($data['bt_experiments_url_query'] ?? '');
update_post_meta( $post_id, 'url_query', $url_query );
$allowed_roles = isset( $data['bt_allowed_roles'] ) ? (array) $data['bt_allowed_roles'] : [];
$allowed_roles = array_map( 'sanitize_text_field', $allowed_roles );
update_post_meta( $post_id, 'bt_allowed_roles', $allowed_roles );
$target_percentage = sanitize_text_field($data['bt_experiments_target_percentage'] ?? '100');
if($target_percentage == '')
$target_percentage = '100';
update_post_meta($post_id,'target_percentage',$target_percentage);
// new target option device size desktop tablet mobile
$target_option_device_size = sanitize_text_field($data['bt_experiments_target_option_device_size'] ?? false);
update_post_meta($post_id,'target_option_device_size',$target_option_device_size);
// log on visible - when enabled, visits are only logged when element becomes visible
$log_on_visible = isset($data['bt_experiments_log_on_visible']) ? '1' : '0';
update_post_meta($post_id,'log_on_visible',$log_on_visible);
// The goal is a page visit (store the page ID) or an element click (store 'selector' and the CSS selector).
if (sanitize_text_field($data['bt_experiments_conversion_page'] ?? '') === 'selector') {
update_post_meta($post_id, 'conversion_page', 'selector');
update_post_meta($post_id, 'conversion_selector', sanitize_text_field($data['bt_experiments_conversion_selector'] ?? ''));
} else {
$conversion_page = intval($data['bt_experiments_conversion_page_selector'] ?? 0);
update_post_meta($post_id,'conversion_page', $conversion_page ? $conversion_page : '');
}
abst_log('Test #' . $post_id . ' ' . ($is_first_save ? 'created' : 'saved') . ' (' . (get_post_meta($post_id, 'test_type', true) ?: 'no type') . ', ' . get_post_status($post_id) . ')');
$this->refresh_conversion_pages();
}
function save_postdata( $post_id ) {
/*
* We need to verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times.
*/
// Check if our nonce is set.
if ( ! isset( $_POST['bt_experiments_inner_custom_box_nonce'] ) )
return $post_id;
$nonce = isset( $_POST['bt_experiments_inner_custom_box_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['bt_experiments_inner_custom_box_nonce'] ) ) : '';
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce, 'myplugin_inner_custom_box' ) )
return $post_id;
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user's permissions.
if ( ! current_user_can( 'edit_post', $post_id ) )
return $post_id;
/* OK, its safe for us to save the data now. */
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Individual fields sanitized inside save_test_config().
$config_result = $this->save_test_config( $post_id, wp_unslash( $_POST ) );
if ( is_wp_error( $config_result ) ) {
wp_die( esc_html( $config_result->get_error_message() ), esc_html__( 'Magic test not saved', 'ab-split-test-lite' ), array( 'back_link' => true ) );
}
}
//refresh conversion pages on trashed/untrashed experiments
function abst_custom_post_updated_messages( $messages ) {
global $post;
if ( ! is_object( $post ) || 'abst_experiments' !== get_post_type( $post->ID ) ) {
return $messages;
}
//if post created was in the last minute its new
$post_time = get_the_time('U', $post->ID);
$is_new = time() - $post_time <= 60;
$status = get_post_status($post->ID);
if ($is_new) {
$message_text = 'Split Test Created.';
} else if ($status === 'publish') {
$message_text = 'Split Test Running.';
} else if ($status === 'pending') {
$message_text = 'Split Test Paused.';
} else if ($status === 'abst_complete') {
$message_text = 'Split Test Marked Complete.';
} else if ($status === 'draft') {
$message_text = 'Split Test Draft Saved.';
} else {
$message_text = 'Split Test Updated.';
}
$cache_message = '';
$detected_caches = abst_get_detected_caches();
$cache_list = implode(', ', $detected_caches);
if ( abst_get_admin_setting('ab_dont_clear_cache_on_update') == '1' ) {
$cache_message = ' IMPORTANT: You\'ll need to manually clear your cache.
The following caches have been detected: ' . $cache_list;
} else {
if ( ! empty( $detected_caches ) ) {
$cache_message = ' These caches have been cleared: ' . esc_html($cache_list) . '.';
}
$cache_message .= ' If you are running any other website caching, clear that now.';
}
// Nothing went live on a refused launch, so there is no cached page to clear.
$full_message = esc_html($message_text) . "
" . $cache_message ;
$custom_messages = array(
1 => $full_message,
4 => $full_message,
6 => $status === 'publish' ? $full_message : esc_html('Split Test Running.') . "
" . $cache_message,
8 => $status === 'pending' ? $full_message : esc_html('Split Test Submitted.') . "
" . $cache_message,
9 => esc_html('Split Test Scheduled.') . "
" . $cache_message,
10 => $status === 'draft' ? $full_message : esc_html('Split Test Draft Saved.') . "
" . $cache_message,
);
$messages['abst_experiments'] = isset($messages['abst_experiments']) && is_array($messages['abst_experiments'])
? array_replace($messages['abst_experiments'], $custom_messages)
: $custom_messages;
$messages['post'][1] = $custom_messages[1]; // Updated
$messages['post'][4] = $custom_messages[4]; // Post updated.
$messages['post'][6] = $custom_messages[6]; // Published
$messages['post'][8] = $custom_messages[8]; // Submitted
$messages['post'][9] = $custom_messages[9]; // Scheduled
$messages['post'][10] = $custom_messages[10]; // Draft updated
return $messages;
}
function experiment_trash_handler( $post_id ) {
//only on experiments
if ( 'abst_experiments' != get_post_type( $post_id ))
return;
$this->refresh_conversion_pages();
}
function refresh_on_update($post_ID, $post_after, $post_before){
$old_title = $post_before->post_title;
$new_title = $post_after->post_title;
// Check if the post title has changed
if ($old_title !== $new_title) {
delete_option('abst_all_testable_posts'); // refresh it
}
// Only experiment changes affect the conversion-page map / embed script.
// post_updated fires for every post type, and page-builder saves (Elementor)
// update the post several times per publish - running the full refresh +
// purge-everything cascade each time can exhaust PHP memory on large sites.
if ($post_after->post_type !== 'abst_experiments') {
// A full-page test's variations point their canonical at the control page's
// URL, stored when the test is saved. If the control page's address changes,
// rebuild that map once, a minute later, instead of leaving the old URL.
if (abst_get_admin_setting('ab_change_canonicals') == 1
&& ($post_before->post_name !== $post_after->post_name || (int) $post_before->post_parent !== (int) $post_after->post_parent || $post_before->post_status !== $post_after->post_status)
&& get_posts(['post_type' => 'abst_experiments', 'post_status' => 'any', 'fields' => 'ids', 'posts_per_page' => 1, 'no_found_rows' => true,
'meta_key' => 'bt_experiments_full_page_default_page', 'meta_value' => (string) $post_ID])) { // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Only runs when a page's address changes.
abst_schedule_canonical_refresh();
}
return;
}
$this->refresh_conversion_pages();
}
function refresh_conversion_pages(){ // and canonicals
// No run-once guard. Saving a test calls this first from post_updated, before
// the test's settings are saved, and again once they are. A guard kept the first,
// stale build, so a test created or edited in the editor lost its page goal,
// traffic % and URL targeting until the next save.
// refresh_on_update() only calls this for test saves, so it stays cheap.
delete_transient('abst_posts_frontend_cache');
$post_ids = get_posts(array(
'post_type' => 'abst_experiments',
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids'
));
$conversion_pages = [];
$canonical_list = [];
foreach ($post_ids as $post_id) {
$conversion_page = get_post_meta($post_id,'conversion_page',true);
$target_percentage = get_post_meta($post_id,'target_percentage',true);
$url_query = get_post_meta($post_id,'url_query',true);
$test_type = get_post_meta($post_id,'test_type',true);
$bt_experiments_full_page_default_page = get_post_meta($post_id,'bt_experiments_full_page_default_page',true);
if($test_type == 'full_page' && abst_get_admin_setting('ab_change_canonicals') == 1)
{
$canonical = get_permalink($bt_experiments_full_page_default_page);// gets default page
$variation_page = absint(get_post_meta($post_id,'variation_page',true));
if($canonical && $variation_page)
$canonical_list[$variation_page] = $canonical; // the variation page's canonical is the original page
}
if($conversion_page == '0') {
continue;
}
if(is_numeric($conversion_page) && (int) $conversion_page > 0)
{
$conversion_pages[$post_id]['conversion_page_id'] = $conversion_page;
}
// add targeting
$conversion_pages[$post_id]['target_percentage'] = $target_percentage;
$conversion_pages[$post_id]['url_query'] = $url_query;
}
update_option('abst_conversion_pages',$conversion_pages);
update_option('abst_test_canonical',$canonical_list);
abst_log('refresh_conversion_pages');
// add_filter('abst_clear_caches', '__return_false'); //disable cache clearing on page and test update
if( apply_filters('abst_clear_caches', true) && (abst_get_admin_setting('ab_dont_clear_cache_on_update') !== '1') )
{
if( class_exists('FLBuilderModel') )
{
abst_log('clearing BB cache');
FLBuilderModel::delete_asset_cache_for_all_posts(); // clear cache
}
// Elementor writes each page's CSS to a file; stale files keep old variation styling.
if ( class_exists( '\Elementor\Plugin' ) && isset( \Elementor\Plugin::$instance->files_manager ) ) {
abst_log('clearing elementor css cache');
\Elementor\Plugin::$instance->files_manager->clear_cache();
}
if (function_exists('sg_cachepress_purge_cache')){
abst_log('clearing sg cache');
sg_cachepress_purge_cache();
}
if(function_exists('nitropack_sdk_purge'))
{
abst_log('clearing nitropack cache');
nitropack_sdk_purge(NULL, NULL, "ABST: Clear after test update");
}
if(class_exists('WP_Optimize'))
{
abst_log('clearing wp optimize cache');
WP_Optimize()->get_page_cache()->purge();
}
if ( class_exists( '\FlyingPress\Purge' ) )
{
abst_log('clearing flyingpress cache');
\FlyingPress\Purge::purge_everything();
}
if ( class_exists( 'autoptimizeCache' ) )
{
abst_log('clearing autoptimize cache');
\autoptimizeCache::clearall();
}
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Third-party Breeze cache action.
do_action( 'breeze_clear_all_cache' );
if ( class_exists( '\WebSharks\CometCache\Classes\ApiBase' ) )
{
abst_log('clearing comet cache');
\WebSharks\CometCache\Classes\ApiBase::clear();
}
if ( class_exists( '\WebSharks\CometCache\Pro\Classes\ApiBase' ) )
{
abst_log('clearing comet pro cache');
\WebSharks\CometCache\Pro\Classes\ApiBase::clear();
}
if ( class_exists( '\WPaaS\Cache' ) && function_exists( 'ccfm_godaddy_purge' ) ) {
abst_log('clearing godaddy cache');
ccfm_godaddy_purge();
}
global $kinsta_cache;
if ( class_exists( '\Kinsta\Cache' ) && ! empty( $kinsta_cache ) )
{
abst_log('clearing kinsta cache');
$kinsta_cache->kinsta_cache_purge->purge_complete_caches();
}
if (class_exists('\LiteSpeed\Purge')) {
abst_log('clearing litespeed cache');
\LiteSpeed\Purge::purge_all();
}
if ( class_exists( 'RapidLoad_Cache' ) && method_exists( 'RapidLoad_Cache', 'clear_site_cache' ) )
{
abst_log('clearing rapidload cache');
\RapidLoad_Cache::clear_site_cache();
}
// W3 Total Cache removed the W3_Plugin_TotalCacheAdmin class years ago, so the
// old check never matched and W3TC was never purged. w3tc_flush_all() is its API.
if ( function_exists( 'w3tc_flush_all' ) ) {
abst_log('clearing total cache');
w3tc_flush_all();
}
// No wp_cache_flush() here. Everything this refresh changes is
// invalidated by name above; a global object-cache flush wipes every
// other cached query on the site.
global $wp_fastest_cache;
if ( ! empty( $wp_fastest_cache ) && method_exists( $wp_fastest_cache, 'deleteCache' ) )
{
abst_log('clearing wp fastest cache');
$wp_fastest_cache->deleteCache( true );
}
if ( function_exists( 'wp_cache_clean_cache' ) )
{
abst_log('clearing wp cache clean cache');
global $file_prefix;
wp_cache_clean_cache( $file_prefix, true );
}
if ( function_exists( 'flush_wp_rocket' ) )
{
abst_log('clearing wp rocket cache');
flush_wp_rocket();
}
if ( function_exists( 'rocket_clean_domain' ) )
{
abst_log('clearing wp rocket domain cache');
rocket_clean_domain();
}
global $nginx_purger;
if ( isset( $nginx_purger ) && method_exists( $nginx_purger, 'purge_all' ) ) {
abst_log('purged nginx');
$nginx_purger->purge_all();
}
if ( class_exists( 'WpeCommon' ) ) {
if ( method_exists( 'WpeCommon', 'purge_memcached' ) )
\WpeCommon::purge_memcached();
if ( method_exists( 'WpeCommon', 'clear_maxcdn_cache' ) )
\WpeCommon::clear_maxcdn_cache();
if ( method_exists( 'WpeCommon', 'purge_varnish_cache' ) )
\WpeCommon::purge_varnish_cache();
abst_log('clearing wpe cache');
}
}// end if clear cache is yes
}
function add_experiment_meta_box() {
// one meta box style
add_meta_box(
'all_boxes',
'Split Test',
array($this,'all_boxes'),
'abst_experiments'
);
}
function create_new_on_page_test(){
// ONLY FOR LOGGD IN USERS
// if user has edittor role, then allow to create experiment
if(!current_user_can('edit_posts'))
wp_die('You do not have the correct permissions to create a test.');
$nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
if (!$nonce || !wp_verify_nonce($nonce, 'abst_create_new_on_page_test')) {
wp_die('Security check failed');
}
// The Magic save gate below validates with helpers from this file, and
// nothing else in an admin-ajax request is guaranteed to have loaded it.
require_once plugin_dir_path(__FILE__) . 'bt-bb-ab-validation.php';
//recieve form data
$data = wp_unslash( $_POST );
//sanitize it!
if(empty($data))
wp_die('No data received.');
$expects_json = !empty($data['abst_magic_mode']) || (isset($_SERVER['HTTP_ACCEPT']) && strpos( sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT'] ) ), 'application/json') !== false);
// Per-object permission checks before wp_insert_post()/wp_update_post(),
// which do not enforce object capabilities themselves.
$experiment_type = get_post_type_object('abst_experiments');
// Save Draft in the Magic Bar sends post_status=draft; ignoring it published the
// test while the editor said "saved as a draft". Builder pop-ups send nothing and
// still create a live test, since it has to appear in their test pickers.
$requested_status = isset($data['post_status']) && in_array($data['post_status'], array('publish', 'draft'), true) ? $data['post_status'] : 'publish';
$is_new_test = isset($data['post_id']) && $data['post_id'] === 'new';
if ($is_new_test) {
if (!$experiment_type || !current_user_can($experiment_type->cap->create_posts)) {
wp_die('You do not have permission to create this test.');
}
// New tests get the requested status (live unless a draft was asked for).
$will_publish = ($requested_status === 'publish');
} else {
$existing_id = isset($data['post_id']) ? absint($data['post_id']) : 0;
$existing_test = $existing_id ? get_post($existing_id) : null;
if (!$existing_test || $existing_test->post_type !== 'abst_experiments'
|| !current_user_can('edit_post', $existing_test->ID)) {
wp_die('You do not have permission to edit this test.');
}
$data['post_id'] = $existing_test->ID;
// Existing auto-drafts are promoted to the requested status below.
$will_publish = $existing_test->post_status === 'auto-draft' && $requested_status === 'publish';
}
if ($will_publish && (!$experiment_type || !current_user_can($experiment_type->cap->publish_posts))) {
wp_die('You do not have permission to publish this test.');
}
// Magic tests: validate the definition BEFORE touching the post. save_test_config()
// silently keeps the previous value when validation fails, so without this gate a bad
// definition still produced a "created" response — publishing a live no-op test (or
// silently dropping an update's edits) while the editor reported success.
if ((($data['test_type'] ?? '') === 'magic' || !empty($data['abst_magic_mode'])) && isset($data['magic_definition']) && $data['magic_definition'] !== '') {
$abst_pre_error = '';
// $data was wp_unslash()ed above, so decode the value as-is.
$abst_pre_decoded = json_decode((string) $data['magic_definition'], true);
if (!is_array($abst_pre_decoded)) {
$abst_pre_error = 'magic_definition is not valid JSON.';
} else {
// An element saved without a scope runs on every page.
foreach ($abst_pre_decoded as $abst_pre_i => $abst_pre_el) {
if (is_array($abst_pre_el)) {
$abst_pre_scope = isset($abst_pre_el['scope']) && is_array($abst_pre_el['scope']) ? $abst_pre_el['scope'] : [];
$abst_pre_has = (isset($abst_pre_scope['page_id']) && $abst_pre_scope['page_id'] !== '')
|| (isset($abst_pre_scope['url']) && trim((string) $abst_pre_scope['url']) !== '');
if (!$abst_pre_has) { $abst_pre_decoded[$abst_pre_i]['scope'] = ['page_id' => '*']; }
}
}
$abst_pre_decoded = abst_prepare_magic_definition_for_write(abst_normalize_magic_definition($abst_pre_decoded));
$abst_pre_validation = abst_validate_magic_definition($abst_pre_decoded);
if (is_wp_error($abst_pre_validation)) {
$abst_pre_error = $abst_pre_validation->get_error_message();
} else {
// Persist exactly the representation that passed validation.
$data['magic_definition'] = wp_json_encode($abst_pre_decoded, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
if ($abst_pre_error !== '') {
abst_log('create_new_on_page_test: magic_definition rejected before save: ' . $abst_pre_error);
if ($expects_json) {
wp_send_json(['config_error' => $abst_pre_error]);
}
wp_die('Test not saved: ' . esc_html($abst_pre_error));
}
}
// Never create/update a test with an empty title — the client keys its success
// handling off the returned title, so '' published a live test with zero feedback.
$abst_post_title = sanitize_text_field($data['post_title'] ?? '');
if ($abst_post_title === '') {
$abst_post_title = 'Magic Test ' . current_time('Y-m-d H:i');
$data['post_title'] = $abst_post_title;
}
$createdNew = false;
if($is_new_test)
{
$my_post = array(
'post_title' => $abst_post_title,
'post_type' => 'abst_experiments',
'post_status' => $requested_status,
'post_date' => current_time('mysql'),
'post_date_gmt'=> current_time('mysql', 1),
);
$data['post_id'] = wp_insert_post( $my_post );
$createdNew = true;
}
else
{
$my_post = array(
'ID' => intval($data['post_id']),
'post_title' => $abst_post_title,
);
// The builder/blocks "Create new Test" iframe pre-creates its post as an
// auto-draft, so this first save arrives with a real post_id and lands here
// instead of the 'new' branch. Without an explicit status wp_update_post()
// only promotes auto-draft to draft, leaving the new test invisible to the
// publish-only experiment dropdowns ("No items found").
if($requested_status === 'draft')
$my_post['post_status'] = 'draft'; // Save Draft, including on an edit of a live test
elseif(in_array(get_post_status(intval($data['post_id'])), array('auto-draft', 'draft'), true))
$my_post['post_status'] = 'publish'; // Start Test on a new or draft test; a paused or complete test keeps its status
wp_update_post( $my_post );
}
$config_result = $this->save_test_config( $data['post_id'], $data);
if (is_wp_error($config_result)) {
if ($expects_json) { wp_send_json(['config_error' => $config_result->get_error_message()]); }
wp_die('Test not saved: ' . esc_html($config_result->get_error_message()));
}
if($expects_json)
{
wp_send_json([
'post_id' => $data['post_id'],
'post_title' => $data['post_title'],
'created' => $createdNew,
'updated' => !$createdNew,
'status' => abst_status_for_api(get_post_status($data['post_id'])),
'edit_url' => admin_url('post.php?post=' . intval($data['post_id']) . '&action=edit'),
]);
}
if($createdNew)
{
// Served as text/html to the builder iframe, so hex-escape the HTML-significant characters.
echo wp_json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
}
else
{
echo "
".esc_html($data['post_title'])."
"; echo "Closing automatically...
"; echo "