← Back
Editing: tmomatic-affiliate.php
<?php /** * Tmomatic - Ticketmaster / Impact affiliate link handling. * * Ticketmaster consolidated its affiliate program onto a single Impact tracking * domain (with new campaign IDs) by the end of 2025. Old links that used the * previous tracking domains / campaign IDs (or the legacy Affiliate Window / * Zanox / Commission Junction networks) now rely on Impact redirects that are * being switched off, breaking click and sale tracking. * * This module: * - Centralises affiliate-link generation so every new post uses a correct, * up-to-date tracking link (tmomatic_build_affiliate_url()). * - Provides a safe admin migration tool to re-point links that are already * stored in posts, post meta and the Affiliate Keyword Replacer list. * * Impact tracking link structure (current standard): * https://{trackingdomain}/c/{publisherId}/{adId}/{campaignId}?u={ENCODED_DESTINATION} */ defined('ABSPATH') or die(); /** * Historical / non-Impact affiliate networks that Ticketmaster used before the * global Impact migration. Links on these networks are considered dead and are * always reduced to (or re-wrapped from) their real destination URL. * * Note: Impact links are NOT identified by domain (Impact reuses domains such * as pxf.io / sjv.io for both old and new programs). Impact links are detected * by their "/c/{mpid}/{adid}/{campaignid}" path instead, and only treated as * "old" when their campaign base differs from the configured new template. * * @return string[] */ function tmomatic_legacy_network_domains() { return apply_filters('tmomatic_legacy_network_domains', array( // Affiliate Window / Awin 'awin1.com', 'zenaps.com', // Zanox 'zanox.com', 'zanox-affiliate.de', // Commission Junction / CJ 'anrdoezrs.net', 'dpbolvw.net', 'jdoqocy.com', 'tkqlhce.com', 'kqzyfj.com', 'qksrv.net', )); } /** * Destination (landing-page) domains that belong to Ticketmaster and its sister * brands. Only these are wrapped when "wrap plain links" is requested, so we * never accidentally rewrite unrelated outbound links in post content. * * @return string[] */ function tmomatic_destination_needles() { return apply_filters('tmomatic_destination_needles', array( 'ticketmaster', 'livenation', 'ticketweb', 'universe.com', 'frontgatetickets', 'moshtix', 'biletix', 'veeps.com', 'quicket', )); } if (!function_exists('tmomatic_str_ends_with')) { function tmomatic_str_ends_with($haystack, $needle) { $needle = (string) $needle; if ($needle === '') { return true; } return substr((string) $haystack, -strlen($needle)) === $needle; } } /** * Decode a percent-encoded value, tolerating values that were encoded more than * once (common when a destination URL is embedded inside another tracking URL). */ function tmomatic_full_urldecode($value) { $value = (string) $value; for ($i = 0; $i < 3; $i++) { if (strpos($value, '%') === false) { break; } $decoded = rawurldecode($value); if ($decoded === $value) { break; } $value = $decoded; } return $value; } /** * Return the canonical Impact campaign base of a tracking URL, i.e. * "scheme://host/c/{mpid}/{adid}/{campaignid}", or '' when the URL is not an * Impact tracking link. */ function tmomatic_impact_base($url) { $url = html_entity_decode(trim((string) $url), ENT_QUOTES); $host = parse_url($url, PHP_URL_HOST); $path = parse_url($url, PHP_URL_PATH); if (!$host || !$path) { return ''; } if (!preg_match('#^(/c/\d+/\d+/\d+)#', $path, $m)) { return ''; } $scheme = parse_url($url, PHP_URL_SCHEME); $scheme = $scheme ? $scheme : 'https'; return $scheme . '://' . strtolower($host) . $m[1]; } /** * Classify an affiliate / destination URL. * * @return array{type:string,destination:string,base:string,host:string} * type is one of: 'impact', 'network', 'plain', 'other'. */ function tmomatic_classify_url($url) { $result = array('type' => 'other', 'destination' => '', 'base' => '', 'host' => ''); $raw = trim((string) $url); if ($raw === '') { return $result; } $decoded = html_entity_decode($raw, ENT_QUOTES); $host = parse_url($decoded, PHP_URL_HOST); if (!$host) { return $result; } $host = strtolower($host); $result['host'] = $host; $query = parse_url($decoded, PHP_URL_QUERY); $params = array(); if ($query) { parse_str($query, $params); } // Case-insensitive parameter lookup. $lookup = array(); foreach ($params as $k => $v) { $lookup[strtolower($k)] = $v; } // Impact tracking link, detected by its /c/mpid/adid/campaignid path. $base = tmomatic_impact_base($decoded); if ($base !== '') { $result['type'] = 'impact'; $result['base'] = $base; if (isset($lookup['u']) && $lookup['u'] !== '') { $dest = tmomatic_full_urldecode($lookup['u']); if (preg_match('#^https?://#i', $dest)) { $result['destination'] = $dest; } } return $result; } // Legacy non-Impact networks (always dead post-migration). foreach (tmomatic_legacy_network_domains() as $d) { if ($host === $d || tmomatic_str_ends_with($host, '.' . $d)) { $result['type'] = 'network'; $dest = ''; foreach (array('ued', 'ulp', 'url', 'murl', 'destination', 'r', 'p') as $key) { if (isset($lookup[$key]) && $lookup[$key] !== '') { $dest = tmomatic_full_urldecode(trim($lookup[$key], '[]')); break; } } if ($dest !== '' && preg_match('#^https?://#i', $dest)) { $result['destination'] = $dest; } return $result; } } // A plain Ticketmaster-family destination URL (no tracking wrapper). foreach (tmomatic_destination_needles() as $needle) { if (strpos($host, $needle) !== false) { $result['type'] = 'plain'; $result['destination'] = $raw; return $result; } } return $result; } /** * Wrap a destination URL in an Impact tracking template. * * @param string $template e.g. https://imp.pxf.io/c/1234567/890123/4567 * @param string $dest destination/landing-page URL * @param string $subids optional extra params (e.g. "subId1=tmomatic") */ function tmomatic_wrap_impact_url($template, $dest, $subids = '') { $template = trim((string) $template); $dest = trim((string) $dest); if ($template === '') { return $dest; } if ($dest === '') { return $template; } // Already pointing at this exact template: leave untouched. if (stripos($dest, $template) === 0) { return $dest; } $sep = (strpos($template, '?') !== false) ? '&' : '?'; $built = $template . $sep . 'u=' . rawurlencode($dest); $subids = trim((string) $subids); if ($subids !== '') { $built .= '&' . ltrim($subids, '&?'); } return $built; } /** * Build the migration / generation configuration from plugin settings, allowing * the migration tool to override individual values. */ function tmomatic_get_affiliate_config($overrides = array()) { $settings = get_option('tmomatic_Main_Settings', array()); if (!is_array($settings)) { $settings = array(); } $config = array( 'mode' => isset($settings['affiliate_link_mode']) ? $settings['affiliate_link_mode'] : 'api', 'template' => isset($settings['impact_tracking_template']) ? trim($settings['impact_tracking_template']) : '', 'subids' => isset($settings['impact_subids']) ? trim($settings['impact_subids']) : '', 'wrap_plain' => false, 'strip_impact' => false, ); $config = array_merge($config, (array) $overrides); $config['template_base'] = $config['template'] !== '' ? tmomatic_impact_base($config['template']) : ''; return $config; } /** * Generation-time builder: turn a raw Discovery API URL into the affiliate link * that should be stored in a freshly generated post. * * In the default "api" mode the URL is returned unchanged (the Discovery API * already wraps links with the partner's Impact tracking when the Publisher ID * is configured in the Ticketmaster Developer Portal). In "wrap" mode the * destination is re-wrapped with the partner's own Impact template. */ function tmomatic_build_affiliate_url($raw_url) { $raw_url = trim((string) $raw_url); if ($raw_url === '') { return $raw_url; } $config = tmomatic_get_affiliate_config(); if ($config['mode'] !== 'wrap' || $config['template'] === '') { return $raw_url; } $info = tmomatic_classify_url($raw_url); $dest = $info['destination'] !== '' ? $info['destination'] : $raw_url; // Don't re-wrap a link that already uses the configured template campaign. if ($info['type'] === 'impact' && $config['template_base'] !== '' && $info['base'] === $config['template_base']) { return $raw_url; } return tmomatic_wrap_impact_url($config['template'], $dest, $config['subids']); } /** * Migrate a single URL according to the supplied config. Returns the (possibly * unchanged) URL. */ function tmomatic_migrate_single_url($url, $config) { $url = trim((string) $url); if ($url === '') { return $url; } $info = tmomatic_classify_url($url); if ($config['template'] !== '') { // Re-point everything onto the partner's current Impact campaign. switch ($info['type']) { case 'impact': // Already on the new campaign? Leave it. if ($config['template_base'] !== '' && $info['base'] === $config['template_base']) { return $url; } if ($info['destination'] === '') { return $url; // No recoverable destination - flagged for manual review. } return tmomatic_wrap_impact_url($config['template'], $info['destination'], $config['subids']); case 'network': if ($info['destination'] === '') { return $url; } return tmomatic_wrap_impact_url($config['template'], $info['destination'], $config['subids']); case 'plain': if (!$config['wrap_plain']) { return $url; } return tmomatic_wrap_impact_url($config['template'], $info['destination'], $config['subids']); } return $url; } // No template configured: "repair" mode. Only unwrap links we know are dead. if ($info['type'] === 'network' && $info['destination'] !== '') { return $info['destination']; } if ($info['type'] === 'impact' && $config['strip_impact'] && $info['destination'] !== '') { return $info['destination']; } return $url; } /** * Migrate every affiliate URL found inside a block of text/HTML. * * @param string $text * @param array $config * @param int $count receives the number of URLs that were changed */ function tmomatic_migrate_text_urls($text, $config, &$count = 0, &$plain_count = null) { if (!is_string($text) || $text === '') { return $text; } return preg_replace_callback( '#https?://[^\s"\'<>()\\\\]+#i', function ($m) use ($config, &$count, &$plain_count) { $orig = $m[0]; // Keep trailing punctuation (e.g. end-of-sentence) out of the URL. $trail = ''; while ($orig !== '' && strpos('.,;!?', substr($orig, -1)) !== false) { $trail = substr($orig, -1) . $trail; $orig = substr($orig, 0, -1); } // Surface plain, un-tracked Ticketmaster links so they are reported // even when wrapping is disabled. if ($plain_count !== null) { $info = tmomatic_classify_url($orig); if ($info['type'] === 'plain') { $plain_count++; } } $new = tmomatic_migrate_single_url($orig, $config); if ($new !== $orig) { $count++; return $new . $trail; } return $m[0]; }, $text ); } /* ------------------------------------------------------------------------- * Admin migration tool * ---------------------------------------------------------------------- */ add_action('admin_menu', 'tmomatic_register_affiliate_migration_page', 20); function tmomatic_register_affiliate_migration_page() { add_submenu_page( 'tmomatic_admin_settings', esc_html__('Affiliate Link Migration', 'tmomatic-ticketmaster-post-generator'), esc_html__('Affiliate Link Migration', 'tmomatic-ticketmaster-post-generator'), 'manage_options', 'tmomatic_affiliate_migration', 'tmomatic_affiliate_migration_page' ); } /** * Count plugin-generated posts that we will scan. */ function tmomatic_affiliate_count_posts() { $q = new WP_Query(array( 'post_type' => 'any', 'post_status' => 'any', 'meta_key' => 'tmomatic_parent_rule', 'fields' => 'ids', 'posts_per_page' => 1, 'no_found_rows' => false, )); return (int) $q->found_posts; } /** * Whether a URL is a Ticketmaster / affiliate link this tool can work with. */ function tmomatic_affiliate_url_is_relevant($url) { $info = tmomatic_classify_url($url); return in_array($info['type'], array('plain', 'impact', 'network'), true); } /** * Strip trailing punctuation accidentally captured from surrounding text. */ function tmomatic_affiliate_trim_url_token($url) { $url = (string) $url; while ($url !== '' && strpos('.,;!?', substr($url, -1)) !== false) { $url = substr($url, 0, -1); } return $url; } /** * Whether a text block contains at least one relevant Ticketmaster/affiliate URL. */ function tmomatic_affiliate_text_has_relevant_links($text) { if (!is_string($text) || $text === '') { return false; } if (!preg_match_all('#https?://[^\s"\'<>()\\\\]+#i', $text, $matches)) { return false; } foreach ($matches[0] as $raw) { if (tmomatic_affiliate_url_is_relevant(tmomatic_affiliate_trim_url_token($raw))) { return true; } } return false; } /** * Whether a single plugin-generated post stores any relevant link. */ function tmomatic_affiliate_post_has_relevant_links($post_id) { foreach (array('tmomatic_post_url', '_EventURL', '_VenueURL') as $key) { $value = get_post_meta($post_id, $key, true); if (is_string($value) && $value !== '' && tmomatic_affiliate_url_is_relevant($value)) { return true; } } $post = get_post($post_id); if ($post instanceof WP_Post && tmomatic_affiliate_text_has_relevant_links($post->post_content)) { return true; } return false; } /** * Count plugin-generated posts that contain at least one relevant link. */ function tmomatic_affiliate_count_posts_with_links() { $total = tmomatic_affiliate_count_posts(); if ($total === 0) { return 0; } $with_links = 0; $offset = 0; $batch = 50; while ($offset < $total) { $q = new WP_Query(array( 'post_type' => 'any', 'post_status' => 'any', 'meta_key' => 'tmomatic_parent_rule', 'fields' => 'ids', 'posts_per_page' => $batch, 'offset' => $offset, 'orderby' => 'ID', 'order' => 'ASC', 'no_found_rows' => true, )); foreach ($q->posts as $post_id) { if (tmomatic_affiliate_post_has_relevant_links($post_id)) { $with_links++; } } $offset += $batch; } return $with_links; } /** * Validate that migration is allowed to run. * * @return true|WP_Error */ function tmomatic_affiliate_validate_migration_ready($config) { if ($config['template'] === '' || $config['template_base'] === '') { return new WP_Error( 'no_template', esc_html__('Migration cannot run: add a valid Impact tracking template (e.g. https://imp.pxf.io/c/{publisherId}/{adId}/{campaignId}) on the Main Settings page first.', 'tmomatic-ticketmaster-post-generator') ); } $posts_with_links = tmomatic_affiliate_count_posts_with_links(); if ($posts_with_links === 0) { return new WP_Error( 'no_links', esc_html__('Migration cannot run: no plugin-generated posts with Ticketmaster or affiliate links were found.', 'tmomatic-ticketmaster-post-generator') ); } return true; } /** * Process one batch of posts. * * @return array summary for the batch */ function tmomatic_affiliate_process_posts_batch($offset, $batch, $apply, $config) { $summary = array( 'scanned' => 0, 'changed' => 0, 'plain' => 0, 'samples' => array(), ); $q = new WP_Query(array( 'post_type' => 'any', 'post_status' => 'any', 'meta_key' => 'tmomatic_parent_rule', 'fields' => 'ids', 'posts_per_page' => $batch, 'offset' => $offset, 'orderby' => 'ID', 'order' => 'ASC', 'no_found_rows' => true, )); $meta_url_keys = array('tmomatic_post_url', '_EventURL', '_VenueURL'); foreach ($q->posts as $post_id) { $summary['scanned']++; $post_changed = false; // 1) Post content. $post = get_post($post_id); if ($post instanceof WP_Post) { $cnt = 0; $plain = 0; $new_content = tmomatic_migrate_text_urls($post->post_content, $config, $cnt, $plain); $summary['plain'] += $plain; if ($cnt > 0 && $new_content !== $post->post_content) { $post_changed = true; if ($apply) { if (get_post_meta($post_id, '_tmomatic_premigration_content', true) === '') { update_post_meta($post_id, '_tmomatic_premigration_content', $post->post_content); } wp_update_post(array( 'ID' => $post_id, 'post_content' => $new_content, )); } if (count($summary['samples']) < 8) { $summary['samples'][] = sprintf( /* translators: 1: post id, 2: number of links */ esc_html__('Post #%1$d content: %2$d link(s)', 'tmomatic-ticketmaster-post-generator'), $post_id, $cnt ); } } } // 2) URL post meta. foreach ($meta_url_keys as $key) { $value = get_post_meta($post_id, $key, true); if (!is_string($value) || $value === '') { continue; } $meta_info = tmomatic_classify_url($value); if ($meta_info['type'] === 'plain') { $summary['plain']++; } $new_value = tmomatic_migrate_single_url($value, $config); if ($new_value !== $value) { $post_changed = true; if ($apply) { $backup_key = '_tmomatic_premigration_' . ltrim($key, '_'); if (get_post_meta($post_id, $backup_key, true) === '') { update_post_meta($post_id, $backup_key, $value); } update_post_meta($post_id, $key, $new_value); } if (count($summary['samples']) < 8) { $summary['samples'][] = sprintf('Post #%d %s', $post_id, $key); } } } if ($post_changed) { $summary['changed']++; } } return $summary; } /** * Migrate the Affiliate Keyword Replacer list (run once, after posts). */ function tmomatic_affiliate_process_keyword_list($apply, $config) { $rules = get_option('tmomatic_keyword_list'); if (!is_array($rules) || empty($rules)) { return array('scanned' => 0, 'changed' => 0); } $changed = 0; $new_rules = array(); foreach ($rules as $request => $value) { if (is_array($value) && isset($value[0]) && is_string($value[0]) && $value[0] !== '') { $new_link = tmomatic_migrate_single_url($value[0], $config); if ($new_link !== $value[0]) { $changed++; $value[0] = $new_link; } } $new_rules[$request] = $value; } if ($changed > 0 && $apply) { if (get_option('tmomatic_keyword_list_premigration', null) === null) { update_option('tmomatic_keyword_list_premigration', $rules, false); } update_option('tmomatic_keyword_list', $new_rules); } return array('scanned' => count($rules), 'changed' => $changed); } /* ------------------------------------------------------------------------- * AJAX handlers * ---------------------------------------------------------------------- */ add_action('wp_ajax_tmomatic_aff_migrate', 'tmomatic_ajax_affiliate_migrate'); function tmomatic_ajax_affiliate_migrate() { if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => esc_html__('Insufficient permissions.', 'tmomatic-ticketmaster-post-generator')), 403); } check_ajax_referer('tmomatic_aff_migrate', 'nonce'); $apply = isset($_POST['apply']) && $_POST['apply'] === '1'; $offset = isset($_POST['offset']) ? max(0, (int) $_POST['offset']) : 0; $batch = isset($_POST['batch']) ? min(100, max(1, (int) $_POST['batch'])) : 20; $config = tmomatic_get_affiliate_config(array( 'wrap_plain' => isset($_POST['wrap_plain']) && $_POST['wrap_plain'] === '1', )); if ($offset === 0) { $ready = tmomatic_affiliate_validate_migration_ready($config); if (is_wp_error($ready)) { wp_send_json_error(array('message' => $ready->get_error_message()), 400); } } $total = tmomatic_affiliate_count_posts(); $summary = tmomatic_affiliate_process_posts_batch($offset, $batch, $apply, $config); $next_offset = $offset + $batch; $done = $next_offset >= $total; $keyword_summary = null; if ($done) { // Final step: migrate the keyword replacer list once. $keyword_summary = tmomatic_affiliate_process_keyword_list($apply, $config); } wp_send_json_success(array( 'apply' => $apply, 'offset' => $offset, 'next_offset' => $next_offset, 'total' => $total, 'done' => $done, 'scanned' => $summary['scanned'], 'changed' => $summary['changed'], 'plain' => $summary['plain'], 'samples' => $summary['samples'], 'keyword_summary' => $keyword_summary, )); } add_action('wp_ajax_tmomatic_aff_rollback', 'tmomatic_ajax_affiliate_rollback'); function tmomatic_ajax_affiliate_rollback() { if (!current_user_can('manage_options')) { wp_send_json_error(array('message' => esc_html__('Insufficient permissions.', 'tmomatic-ticketmaster-post-generator')), 403); } check_ajax_referer('tmomatic_aff_migrate', 'nonce'); $offset = isset($_POST['offset']) ? max(0, (int) $_POST['offset']) : 0; $batch = isset($_POST['batch']) ? min(100, max(1, (int) $_POST['batch'])) : 20; $q = new WP_Query(array( 'post_type' => 'any', 'post_status' => 'any', 'meta_key' => 'tmomatic_parent_rule', 'fields' => 'ids', 'posts_per_page' => $batch, 'offset' => $offset, 'orderby' => 'ID', 'order' => 'ASC', 'no_found_rows' => true, )); $restored = 0; $meta_url_keys = array('tmomatic_post_url', '_EventURL', '_VenueURL'); foreach ($q->posts as $post_id) { $backup_content = get_post_meta($post_id, '_tmomatic_premigration_content', true); if (is_string($backup_content) && $backup_content !== '') { wp_update_post(array('ID' => $post_id, 'post_content' => $backup_content)); delete_post_meta($post_id, '_tmomatic_premigration_content'); $restored++; } foreach ($meta_url_keys as $key) { $backup_key = '_tmomatic_premigration_' . ltrim($key, '_'); $backup_val = get_post_meta($post_id, $backup_key, true); if (is_string($backup_val) && $backup_val !== '') { update_post_meta($post_id, $key, $backup_val); delete_post_meta($post_id, $backup_key); $restored++; } } } $total = tmomatic_affiliate_count_posts(); $next_offset = $offset + $batch; $done = $next_offset >= $total; if ($done) { $backup_rules = get_option('tmomatic_keyword_list_premigration', null); if ($backup_rules !== null) { update_option('tmomatic_keyword_list', $backup_rules); delete_option('tmomatic_keyword_list_premigration'); } } wp_send_json_success(array( 'offset' => $offset, 'next_offset' => $next_offset, 'total' => $total, 'done' => $done, 'restored' => $restored, )); } /* ------------------------------------------------------------------------- * Admin page UI * ---------------------------------------------------------------------- */ function tmomatic_affiliate_migration_page() { if (!current_user_can('manage_options')) { return; } $config = tmomatic_get_affiliate_config(); $total = tmomatic_affiliate_count_posts(); $posts_with_links = tmomatic_affiliate_count_posts_with_links(); $nonce = wp_create_nonce('tmomatic_aff_migrate'); $has_tpl = $config['template'] !== ''; $has_valid_tpl = $has_tpl && $config['template_base'] !== ''; $can_migrate = $has_valid_tpl && $posts_with_links > 0; ?> <div class="wrap"> <h1><?php echo esc_html__('Ticketmaster Affiliate Link Migration', 'tmomatic-ticketmaster-post-generator'); ?></h1> <p><?php echo esc_html__('Ticketmaster moved its affiliate program onto a single, consolidated Impact tracking domain (with new campaign IDs). Links generated before 2026 may now be broken because the old Impact redirects are being switched off. This tool re-points the affiliate links already stored in your generated posts, post meta and the Affiliate Keyword Replacer list.', 'tmomatic-ticketmaster-post-generator'); ?></p> <?php if (!$has_valid_tpl): ?> <div class="notice notice-error"><p><?php echo esc_html__('An Impact tracking template is required before you can run this tool. Set it on the Main Settings page (e.g. https://imp.pxf.io/c/{publisherId}/{adId}/{campaignId}).', 'tmomatic-ticketmaster-post-generator'); ?> <a href="<?php echo esc_url(admin_url('admin.php?page=tmomatic_admin_settings')); ?>"><?php echo esc_html__('Open Main Settings', 'tmomatic-ticketmaster-post-generator'); ?></a></p></div> <?php elseif ($posts_with_links === 0): ?> <div class="notice notice-warning"><p><?php echo esc_html__('No plugin-generated posts with Ticketmaster or affiliate links were found. Nothing to migrate.', 'tmomatic-ticketmaster-post-generator'); ?></p></div> <?php endif; ?> <h2><?php echo esc_html__('Current configuration', 'tmomatic-ticketmaster-post-generator'); ?></h2> <table class="widefat striped" style="max-width:760px;"> <tbody> <tr> <td><strong><?php echo esc_html__('Plugin-generated posts to scan', 'tmomatic-ticketmaster-post-generator'); ?></strong></td> <td><?php echo esc_html((string) $total); ?></td> </tr> <tr> <td><strong><?php echo esc_html__('Posts with Ticketmaster / affiliate links', 'tmomatic-ticketmaster-post-generator'); ?></strong></td> <td><?php echo esc_html((string) $posts_with_links); ?></td> </tr> <tr> <td><strong><?php echo esc_html__('Impact tracking template', 'tmomatic-ticketmaster-post-generator'); ?></strong></td> <td> <?php if ($has_tpl): ?> <code><?php echo esc_html($config['template']); ?></code> <?php if (!$has_valid_tpl): ?> <br/><span style="color:#b32d2e;"><?php echo esc_html__('Invalid: expected an Impact tracking link with a /c/{publisherId}/{adId}/{campaignId} path (e.g. imp.pxf.io).', 'tmomatic-ticketmaster-post-generator'); ?></span> <?php endif; ?> <?php else: ?> <em><?php echo esc_html__('Not set - required to run migration.', 'tmomatic-ticketmaster-post-generator'); ?></em> <br/><a href="<?php echo esc_url(admin_url('admin.php?page=tmomatic_admin_settings')); ?>"><?php echo esc_html__('Set it on the Main Settings page', 'tmomatic-ticketmaster-post-generator'); ?></a> <?php endif; ?> </td> </tr> </tbody> </table> <h2><?php echo esc_html__('Options', 'tmomatic-ticketmaster-post-generator'); ?></h2> <p> <label> <input type="checkbox" id="tmomatic_wrap_plain" <?php disabled(!$can_migrate); ?> /> <?php echo esc_html__('Also wrap plain Ticketmaster URLs that have no tracking yet', 'tmomatic-ticketmaster-post-generator'); ?> </label> </p> <h2><?php echo esc_html__('Run', 'tmomatic-ticketmaster-post-generator'); ?></h2> <p> <button type="button" class="button button-secondary" id="tmomatic_aff_preview" <?php disabled(!$can_migrate); ?>><?php echo esc_html__('1. Preview (no changes)', 'tmomatic-ticketmaster-post-generator'); ?></button> <button type="button" class="button button-primary" id="tmomatic_aff_apply" <?php disabled(!$can_migrate); ?>><?php echo esc_html__('2. Apply migration', 'tmomatic-ticketmaster-post-generator'); ?></button> <button type="button" class="button" id="tmomatic_aff_rollback"><?php echo esc_html__('Roll back last migration', 'tmomatic-ticketmaster-post-generator'); ?></button> </p> <div id="tmomatic_aff_progress" style="display:none;margin:12px 0;"> <progress id="tmomatic_aff_bar" value="0" max="100" style="width:420px;height:20px;"></progress> <span id="tmomatic_aff_pct">0%</span> </div> <div id="tmomatic_aff_results" style="margin-top:12px;"></div> <script type="text/javascript"> (function () { var ajaxurl = <?php echo wp_json_encode(admin_url('admin-ajax.php')); ?>; var nonce = <?php echo wp_json_encode($nonce); ?>; var batch = 20; var canMigrate = <?php echo $can_migrate ? 'true' : 'false'; ?>; var btnPreview = document.getElementById('tmomatic_aff_preview'); var btnApply = document.getElementById('tmomatic_aff_apply'); var btnRollback = document.getElementById('tmomatic_aff_rollback'); var results = document.getElementById('tmomatic_aff_results'); var progressBox = document.getElementById('tmomatic_aff_progress'); var bar = document.getElementById('tmomatic_aff_bar'); var pct = document.getElementById('tmomatic_aff_pct'); function setButtons(busy) { btnPreview.disabled = busy || !canMigrate; btnApply.disabled = busy || !canMigrate; btnRollback.disabled = busy; } function migrationBlockedMessage() { <?php if (!$has_valid_tpl): ?> return <?php echo wp_json_encode(esc_html__('Add a valid Impact tracking template on the Main Settings page before running migration.', 'tmomatic-ticketmaster-post-generator')); ?>; <?php elseif ($posts_with_links === 0): ?> return <?php echo wp_json_encode(esc_html__('No plugin-generated posts with Ticketmaster or affiliate links were found.', 'tmomatic-ticketmaster-post-generator')); ?>; <?php else: ?> return <?php echo wp_json_encode(esc_html__('Migration cannot run with the current configuration.', 'tmomatic-ticketmaster-post-generator')); ?>; <?php endif; ?> } function post(data) { var body = new URLSearchParams(); Object.keys(data).forEach(function (k) { body.append(k, data[k]); }); return fetch(ajaxurl, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, body: body.toString() }).then(function (r) { return r.json(); }); } function updateProgress(offset, total) { var done = total > 0 ? Math.min(100, Math.round((offset / total) * 100)) : 100; bar.value = done; pct.textContent = done + '%'; } function run(action, apply) { if (action === 'tmomatic_aff_migrate' && !canMigrate) { results.innerHTML = '<div class="notice notice-error"><p>' + migrationBlockedMessage() + '</p></div>'; return; } setButtons(true); progressBox.style.display = 'block'; results.innerHTML = ''; var totalScanned = 0, totalChanged = 0, totalRestored = 0, totalPlain = 0, samples = []; var wrapPlain = document.getElementById('tmomatic_wrap_plain').checked ? '1' : '0'; function step(offset) { var payload = { action: action, nonce: nonce, offset: offset, batch: batch }; if (action === 'tmomatic_aff_migrate') { payload.apply = apply ? '1' : '0'; payload.wrap_plain = wrapPlain; } return post(payload).then(function (res) { if (!res || !res.success) { var msg = (res && res.data && res.data.message) ? res.data.message : 'Request failed.'; results.innerHTML = '<div class="notice notice-error"><p>' + msg + '</p></div>'; setButtons(false); return; } var d = res.data; if (typeof d.scanned !== 'undefined') { totalScanned += d.scanned; } if (typeof d.changed !== 'undefined') { totalChanged += d.changed; } if (typeof d.plain !== 'undefined') { totalPlain += d.plain; } if (typeof d.restored !== 'undefined') { totalRestored += d.restored; } if (d.samples && d.samples.length) { samples = samples.concat(d.samples); } updateProgress(Math.min(d.next_offset, d.total), d.total); if (!d.done) { step(d.next_offset); } else { updateProgress(d.total, d.total); finish(action, apply, d, totalScanned, totalChanged, totalRestored, totalPlain, samples); setButtons(false); } }).catch(function (e) { results.innerHTML = '<div class="notice notice-error"><p>' + (e && e.message ? e.message : 'Network error.') + '</p></div>'; setButtons(false); }); } step(0); } function finish(action, apply, d, scanned, changed, restored, plain, samples) { var html = '<div class="notice notice-success"><p>'; if (action === 'tmomatic_aff_rollback') { html += <?php echo wp_json_encode(esc_html__('Rollback complete. Restored items:', 'tmomatic-ticketmaster-post-generator')); ?> + ' ' + restored + '.'; } else { html += (apply ? <?php echo wp_json_encode(esc_html__('Migration applied.', 'tmomatic-ticketmaster-post-generator')); ?> : <?php echo wp_json_encode(esc_html__('Preview complete (no changes were written).', 'tmomatic-ticketmaster-post-generator')); ?>); html += ' ' + <?php echo wp_json_encode(esc_html__('Posts scanned:', 'tmomatic-ticketmaster-post-generator')); ?> + ' ' + scanned + ', '; html += <?php echo wp_json_encode(esc_html__('posts with updated links:', 'tmomatic-ticketmaster-post-generator')); ?> + ' ' + changed + '.'; if (d.keyword_summary) { html += ' ' + <?php echo wp_json_encode(esc_html__('Keyword replacer links updated:', 'tmomatic-ticketmaster-post-generator')); ?> + ' ' + d.keyword_summary.changed + '.'; } } html += '</p>'; if (action === 'tmomatic_aff_migrate' && plain > 0 && changed === 0) { html += '<p>' + <?php echo wp_json_encode(esc_html__('Plain (un-tracked) Ticketmaster links found:', 'tmomatic-ticketmaster-post-generator')); ?> + ' ' + plain + '. ' + <?php echo wp_json_encode(esc_html__('Tick "Also wrap plain Ticketmaster URLs" and run again to add affiliate tracking to them.', 'tmomatic-ticketmaster-post-generator')); ?> + '</p>'; } else if (action === 'tmomatic_aff_migrate' && plain > 0) { html += '<p>' + <?php echo wp_json_encode(esc_html__('Plain (un-tracked) Ticketmaster links also found:', 'tmomatic-ticketmaster-post-generator')); ?> + ' ' + plain + '.</p>'; } if (samples && samples.length) { html += '<ul style="list-style:disc;margin-left:20px;">'; samples.forEach(function (s) { html += '<li>' + s + '</li>'; }); html += '</ul>'; } html += '</div>'; results.innerHTML = html; } btnPreview.addEventListener('click', function () { run('tmomatic_aff_migrate', false); }); btnApply.addEventListener('click', function () { if (window.confirm(<?php echo wp_json_encode(esc_html__('Apply the migration now? Original content is backed up so you can roll back.', 'tmomatic-ticketmaster-post-generator')); ?>)) { run('tmomatic_aff_migrate', true); } }); btnRollback.addEventListener('click', function () { if (window.confirm(<?php echo wp_json_encode(esc_html__('Roll back the last migration from backups?', 'tmomatic-ticketmaster-post-generator')); ?>)) { run('tmomatic_aff_rollback', false); } }); })(); </script> </div> <?php }
Save File
Cancel