← Back
Editing: seo-url-replacer.php
<?php /** * Plugin Name: SEO URL Replacer * Plugin URI: https://github.com/seu-usuario/seo-url-replacer * Description: Substituição em lote de URLs com suporte a dados serializados (ACF, Elementor), dry run, health check e log de auditoria. * Version: 2.2.2 * Author: Seu Nome * License: GPL-2.0+ * Text Domain: seo-url-replacer */ defined('ABSPATH') || exit; define('SUR_VERSION', '2.2.2'); define('SUR_PLUGIN_DIR', plugin_dir_path(__FILE__)); define('SUR_PLUGIN_URL', plugin_dir_url(__FILE__)); add_action('admin_menu', function () { add_management_page('SEO URL Replacer', 'SEO URL Replacer', 'manage_options', 'seo-url-replacer', 'sur_render_admin_page'); }); add_action('admin_enqueue_scripts', function ($hook) { if ($hook !== 'tools_page_seo-url-replacer') return; wp_enqueue_style('sur-admin-css', SUR_PLUGIN_URL . 'assets/admin.css', [], SUR_VERSION); wp_enqueue_script('sur-admin-js', SUR_PLUGIN_URL . 'assets/admin.js', ['jquery'], SUR_VERSION, true); wp_localize_script('sur-admin-js', 'SUR', [ 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonceBatch' => wp_create_nonce('sur_batch_replace'), 'nonceCheck' => wp_create_nonce('sur_health_check'), ]); }); function sur_render_admin_page() { if (! current_user_can('manage_options')) { wp_die('Acesso negado.'); } ?> <div class="wrap sur-wrap"> <h1>🔗 SEO URL Replacer</h1> <p class="sur-subtitle">Substitua URLs em lote com segurança — suporte a dados serializados (ACF, Elementor, temas customizados).</p> <!-- CARD 1: Fonte de mapeamentos --> <div class="sur-card"> <h2>1. Mapeamentos de URL</h2> <!-- Abas: CSV | Manual --> <div class="sur-tabs"> <button class="sur-tab sur-tab-active" id="surTabCsv" type="button">📄 Upload CSV</button> <button class="sur-tab" id="surTabManual" type="button">✏️ Entrada Manual</button> </div> <!-- Painel CSV --> <div id="surPanelCsv"> <p style="margin-top:12px">O arquivo deve ter duas colunas: <strong>DE</strong> (URL antiga) e <strong>PARA</strong> (URL nova). Cabeçalho na primeira linha.</p> <div class="sur-upload-area" id="surDropZone"> <span class="dashicons dashicons-upload"></span> <p>Arraste o CSV aqui ou <label for="surCsvFile" class="sur-link">clique para selecionar</label></p> <input type="file" id="surCsvFile" accept=".csv" style="display:none"> </div> </div> <!-- Painel Manual --> <div id="surPanelManual" style="display:none"> <p style="margin-top:12px">Adicione os pares de substituição manualmente. Clique em <strong>+ Adicionar linha</strong> para incluir mais.</p> <div id="surManualRows"> <div class="sur-manual-header"> <span>DE (URL antiga)</span> <span>PARA (URL nova)</span> <span></span> </div> <!-- Linha inicial gerada pelo JS --> </div> <div style="margin-top:10px;display:flex;gap:8px;flex-wrap:wrap"> <button type="button" id="surAddRowBtn" class="button">+ Adicionar linha</button> <button type="button" id="surApplyManualBtn" class="button button-primary">↩ Carregar mapeamentos</button> <button type="button" id="surClearManualBtn" class="button">🗑 Limpar tudo</button> </div> </div> <!-- Prévia unificada (CSV e Manual) --> <div id="surCsvPreview" style="display:none"> <h3 style="margin-top:16px">Prévia (<span id="surEntryCount">0</span> entradas após deduplicação)</h3> <div class="sur-table-wrap sur-table-scroll"> <table class="widefat sur-preview-table"> <thead> <tr><th>#</th><th>DE (URL antiga)</th><th>PARA (URL nova)</th></tr> </thead> <tbody id="surPreviewBody"></tbody> </table> </div> </div> </div> <!-- CARD 2: Opções --> <div class="sur-card" id="surOptionsCard" style="display:none"> <h2>2. Opções de Execução</h2> <label class="sur-toggle"> <input type="checkbox" id="surDryRun" checked> <span class="sur-toggle-slider"></span> <strong>Modo Simulação (Dry Run)</strong> — conta ocorrências sem gravar no banco </label> <p class="sur-hint">Recomendado: rode em simulação primeiro para conferir o impacto antes de aplicar.</p> <label class="sur-toggle"> <input type="checkbox" id="surExact" checked> <span class="sur-toggle-slider"></span> <strong>Modo Exato</strong> — substitui só a URL completa (recomendado) </label> <p class="sur-hint">Quando ligado, NÃO expande variações de caminho relativo (ex.: <code>/account</code>, <code>/lojas</code>). Isso evita que uma palavra curta corresponda dentro de outros links. Desligue só se suas URLs estiverem salvas como links relativos.</p> <div class="sur-tables-opt"> <strong style="width:100%;display:block;margin-bottom:8px">Tabelas a processar:</strong> <label><input type="checkbox" class="sur-table-chk" value="posts" checked> wp_posts — conteúdo de posts/páginas</label> <label><input type="checkbox" class="sur-table-chk" value="posts_title"> wp_posts — excerpts</label> <label><input type="checkbox" class="sur-table-chk" value="postmeta" checked> wp_postmeta — ACF / Elementor / Yoast</label> <label><input type="checkbox" class="sur-table-chk" value="options" checked> wp_options — configurações globais / menus</label> <label><input type="checkbox" class="sur-table-chk" value="termmeta"> wp_termmeta — metadados de categorias/tags</label> <label><input type="checkbox" class="sur-table-chk" value="usermeta"> wp_usermeta — metadados de usuários</label> <label><input type="checkbox" class="sur-table-chk" value="comments"> wp_comments — conteúdo de comentários</label> </div> <div class="sur-batch-row"> <label for="surBatchSize"><strong>Registros por lote:</strong></label> <select id="surBatchSize"> <option value="10">10 — servidor lento / shared hosting</option> <option value="25">25 — conservador</option> <option value="50" selected>50 — padrão recomendado</option> <option value="100">100 — servidor rápido</option> <option value="200">200 — VPS / dedicado</option> <option value="500">500 — máximo (cuidado com timeout)</option> </select> <span class="sur-hint" style="margin:0">Se ocorrer erro 500, reduza este valor.</span> </div> <button id="surStartBtn" class="button button-primary button-large">▶ Iniciar Processamento</button> </div> <!-- CARD 3: Progresso --> <div class="sur-card" id="surProgressCard" style="display:none"> <h2>3. Progresso</h2> <p id="surProgressMsg">Calculando totais...</p> <div class="sur-progress-outer"> <div class="sur-progress-inner" id="surProgressBar" style="width:0%">0%</div> </div> <p id="surTableMsg" style="color:#64748B;font-size:.85rem"></p> <div id="surAuditLog" class="sur-log"></div> <!-- Ações pós-conclusão --> <div id="surPostActions" style="display:none;margin-top:16px;display:none;gap:10px;flex-wrap:wrap"> <button id="surApplyRealBtn" class="button button-primary" style="display:none"> ✅ Aplicar de verdade (desativar Dry Run e rodar novamente) </button> <button id="surNewRunBtn" class="button button-secondary"> 🔄 Nova análise com o mesmo CSV </button> <button id="surResetBtn" class="button"> ↺ Reiniciar tudo (novo CSV) </button> </div> </div> <!-- CARD 4: Health Check --> <div class="sur-card" id="surHealthCard" style="display:none"> <h2>4. Health Check das Novas URLs</h2> <p>Verificando status HTTP de cada URL de destino mapeada no CSV...</p> <div class="sur-progress-outer"> <div class="sur-progress-inner" id="surHealthBar" style="width:0%">0%</div> </div> <div class="sur-table-wrap sur-table-scroll"> <table class="widefat"> <thead> <tr><th>URL Destino</th><th>Status HTTP</th><th>Resultado</th></tr> </thead> <tbody id="surHealthBody"></tbody> </table> </div> </div> </div> <?php } // ============================================================================= // HELPER: EXPANDE URLs (Absolutas, Relativas e variações JSON escapadas) // Garante que URLs armazenadas em diferentes formatos sejam todas substituídas. // ============================================================================= function sur_expand_mappings(array $mappings, bool $exact = false): array { $expanded = []; foreach ($mappings as $map) { // 1. URL completa exata $expanded[] = $map; // 2. Versão JSON-escapada (Elementor armazena \/ em vez de /) $from_esc = str_replace('/', '\/', $map['from']); $to_esc = str_replace('/', '\/', $map['to']); if ($from_esc !== $map['from']) { $expanded[] = ['from' => $from_esc, 'to' => $to_esc]; } // No MODO EXATO paramos aqui: só a URL completa (e sua forma escapada) // são substituídas. Pulamos as variações de caminho relativo abaixo, // que geram chaves curtas (ex.: /account, /lojas) capazes de casar // dentro de outros links e corromper URLs não relacionadas. if ($exact) { continue; } // 3. Apenas o path relativo (/caminho/da/pagina/) $from_path = parse_url($map['from'], PHP_URL_PATH); $to_path = parse_url($map['to'], PHP_URL_PATH); if (! empty($from_path) && $from_path !== $map['from'] && $from_path !== '/') { $to_path = ! empty($to_path) ? $to_path : '/'; $expanded[] = ['from' => $from_path, 'to' => $to_path]; // 4. Path relativo também JSON-escapado $from_path_esc = str_replace('/', '\/', $from_path); $to_path_esc = str_replace('/', '\/', $to_path); if ($from_path_esc !== $from_path) { $expanded[] = ['from' => $from_path_esc, 'to' => $to_path_esc]; } } } // Remove duplicatas e ordena da string mais longa para a mais curta // (evita que uma URL-base curta seja substituída antes de uma mais específica) $unique = array_map('unserialize', array_unique(array_map('serialize', $expanded))); usort($unique, function ($a, $b) { return strlen($b['from']) - strlen($a['from']); }); return $unique; } // ============================================================================= // FONTES DE DADOS — tabelas, colunas e SQLs paginados // ============================================================================= function sur_get_table_sources(array $tables, array $from_urls = []): array { global $wpdb; $all_sources = [ 'posts' => [ 'label' => 'wp_posts (post_content)', 'id_col' => 'ID', 'value_col' => 'post_content', 'table' => $wpdb->posts, 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status NOT IN ('auto-draft','trash') AND post_content != ''", 'select_sql' => "SELECT ID as record_id, post_content as record_value FROM {$wpdb->posts} WHERE post_status NOT IN ('auto-draft','trash') AND post_content != '' LIMIT %d OFFSET %d", ], 'posts_title' => [ 'label' => 'wp_posts (post_excerpt)', 'id_col' => 'ID', 'value_col' => 'post_excerpt', 'table' => $wpdb->posts, 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status NOT IN ('auto-draft','trash') AND post_excerpt != ''", 'select_sql' => "SELECT ID as record_id, post_excerpt as record_value FROM {$wpdb->posts} WHERE post_status NOT IN ('auto-draft','trash') AND post_excerpt != '' LIMIT %d OFFSET %d", ], 'postmeta' => [ 'label' => 'wp_postmeta', 'id_col' => 'meta_id', 'value_col' => 'meta_value', 'table' => $wpdb->postmeta, 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_value != '' AND meta_value IS NOT NULL", 'select_sql' => "SELECT meta_id as record_id, meta_value as record_value FROM {$wpdb->postmeta} WHERE meta_value != '' AND meta_value IS NOT NULL LIMIT %d OFFSET %d", ], 'options' => [ 'label' => 'wp_options', 'id_col' => 'option_id', 'value_col' => 'option_value', 'table' => $wpdb->options, 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->options} WHERE option_name NOT LIKE '%\\_transient\\_%' AND option_name NOT LIKE '%\\_site\\_transient\\_%' AND option_name NOT IN ('siteurl','home','blogname','blogdescription','admin_email','auth_key','secure_auth_key','logged_in_key','nonce_key')", 'select_sql' => "SELECT option_id as record_id, option_value as record_value FROM {$wpdb->options} WHERE option_name NOT LIKE '%\\_transient\\_%' AND option_name NOT LIKE '%\\_site\\_transient\\_%' AND option_name NOT IN ('siteurl','home','blogname','blogdescription','admin_email','auth_key','secure_auth_key','logged_in_key','nonce_key') LIMIT %d OFFSET %d", ], 'termmeta' => [ 'label' => 'wp_termmeta', 'id_col' => 'meta_id', 'value_col' => 'meta_value', 'table' => $wpdb->termmeta, 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->termmeta} WHERE meta_value != '' AND meta_value IS NOT NULL", 'select_sql' => "SELECT meta_id as record_id, meta_value as record_value FROM {$wpdb->termmeta} WHERE meta_value != '' AND meta_value IS NOT NULL LIMIT %d OFFSET %d", ], 'usermeta' => [ 'label' => 'wp_usermeta', 'id_col' => 'umeta_id', 'value_col' => 'meta_value', 'table' => $wpdb->usermeta, 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->usermeta} WHERE meta_value != '' AND meta_value IS NOT NULL", 'select_sql' => "SELECT umeta_id as record_id, meta_value as record_value FROM {$wpdb->usermeta} WHERE meta_value != '' AND meta_value IS NOT NULL LIMIT %d OFFSET %d", ], 'comments' => [ 'label' => 'wp_comments', 'id_col' => 'comment_ID', 'value_col' => 'comment_content', 'table' => $wpdb->comments, 'count_sql' => "SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_content != ''", 'select_sql' => "SELECT comment_ID as record_id, comment_content as record_value FROM {$wpdb->comments} WHERE comment_content != '' LIMIT %d OFFSET %d", ], ]; // ── Filtro LIKE otimizado ────────────────────────────────────── // PROBLEMA com 600 URLs: gerar 600+ cláusulas LIKE cria queries enormes // que o MySQL pode silenciosamente ignorar ou tratar como erro. // // SOLUÇÃO: extrair apenas os DOMÍNIOS únicos das URLs para o LIKE. // Ex: 600 URLs do mesmo domínio viram apenas 1 cláusula LIKE '%dominio.com%'. // O PHP depois faz a verificação exata linha a linha via sur_recursive_replace. // Máximo de 20 cláusulas LIKE para manter a query enxuta. $like_domains = []; if (! empty($from_urls)) { foreach ($from_urls as $url) { $host = parse_url($url, PHP_URL_HOST); if ($host) { $like_domains[] = $host; } else { // URL relativa: pega o primeiro segmento do path $path = ltrim($url, '/'); $segments = explode('/', $path); if (! empty($segments[0])) { $like_domains[] = $segments[0]; } } } $like_domains = array_unique($like_domains); $like_domains = array_slice($like_domains, 0, 20); // máximo 20 domínios } $selected = []; foreach ($tables as $key) { if (isset($all_sources[$key])) { $src = $all_sources[$key]; if (! empty($like_domains)) { $src['count_sql'] = sur_inject_like_filter($src['count_sql'], $src['value_col'], $like_domains); $src['select_sql'] = sur_inject_like_filter($src['select_sql'], $src['value_col'], $like_domains); } $selected[$key] = $src; } } return $selected; } /** * Injeta cláusulas LIKE no SQL. * Recebe domínios (não URLs completas) para manter a query curta. */ function sur_inject_like_filter(string $sql, string $col, array $terms): string { global $wpdb; if (empty($terms)) return $sql; // Constrói os LIKE com valores literais já escapados (esc_like + esc_sql), // SEM usar $wpdb->prepare. Isso é essencial porque o SQL resultante NÃO é // passado por prepare na execução — e o wp_options já contém '%' literais // (em '%\_transient\_%') que o prepare interpretaria como placeholders, // corrompendo a query e gerando erro 500. $likes = []; foreach ($terms as $term) { $esc = esc_sql($wpdb->esc_like($term)); $likes[] = "{$col} LIKE '%{$esc}%'"; } $like_sql = ' AND (' . implode(' OR ', $likes) . ')'; if (stripos($sql, 'LIMIT') !== false) { return preg_replace('/\s*LIMIT\s+%d\s+OFFSET\s+%d\s*$/i', $like_sql . ' LIMIT %d OFFSET %d', $sql); } return $sql . $like_sql; } // ============================================================================= // AJAX: CONTAR TOTAIS // ============================================================================= add_action('wp_ajax_sur_count_totals', 'sur_ajax_count_totals'); function sur_ajax_count_totals() { check_ajax_referer('sur_batch_replace', '_wpnonce'); if (! current_user_can('manage_options')) { wp_send_json_error('Permissão negada.'); } $tables = json_decode(stripslashes(isset($_POST['tables']) ? $_POST['tables'] : '[]'), true); $mappings = json_decode(stripslashes(isset($_POST['mappings']) ? $_POST['mappings'] : '[]'), true); $exact = ! empty($_POST['exact']); $mappings = sur_expand_mappings($mappings, $exact); $from_urls = array_column($mappings, 'from'); $sources = sur_get_table_sources($tables, $from_urls); global $wpdb; $totals = []; $grand_total = 0; foreach ($sources as $key => $src) { $count = (int) $wpdb->get_var($src['count_sql']); $totals[$key] = $count; $grand_total += $count; } wp_send_json_success(['totals' => $totals, 'grand_total' => $grand_total]); } // ============================================================================= // AJAX: PROCESSAMENTO EM LOTE // Paginação real via LIMIT/OFFSET — nunca carrega a tabela inteira em memória. // ============================================================================= add_action('wp_ajax_sur_batch_replace', 'sur_ajax_batch_replace'); function sur_ajax_batch_replace() { check_ajax_referer('sur_batch_replace', '_wpnonce'); if (! current_user_can('manage_options')) { wp_send_json_error('Permissão negada.'); } // wp_options costuma ter blobs serializados grandes (menus, Elementor, // configs de tema). Damos mais fôlego de tempo e memória ao lote. @set_time_limit(0); wp_raise_memory_limit('admin'); // Converte erros fatais (timeout, memória, recursão) num JSON legível // informando qual registro estava sendo processado — em vez de um 500 opaco. $GLOBALS['sur_ctx'] = ['table' => '—', 'record_id' => '—']; register_shutdown_function(function () { $err = error_get_last(); $fatal = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR]; if ($err && in_array($err['type'], $fatal, true)) { $ctx = isset($GLOBALS['sur_ctx']) ? $GLOBALS['sur_ctx'] : []; if (! headers_sent()) { @header('Content-Type: application/json; charset=utf-8'); @http_response_code(200); } echo wp_json_encode([ 'success' => false, 'data' => sprintf( 'Erro fatal em %s (registro id=%s): %s', isset($ctx['table']) ? $ctx['table'] : '?', isset($ctx['record_id']) ? $ctx['record_id'] : '?', $err['message'] ), ]); } }); $mappings = json_decode(stripslashes(isset($_POST['mappings']) ? $_POST['mappings'] : '[]'), true); $tables = json_decode(stripslashes(isset($_POST['tables']) ? $_POST['tables'] : '[]'), true); $totals = json_decode(stripslashes(isset($_POST['totals']) ? $_POST['totals'] : '{}'), true); $table_key = isset($_POST['table_key']) ? sanitize_key($_POST['table_key']) : ''; $offset = intval(isset($_POST['offset']) ? $_POST['offset'] : 0); $batch = intval(isset($_POST['batch']) ? $_POST['batch'] : 50); $dry_run = ! empty($_POST['dry_run']); $exact = ! empty($_POST['exact']); if (empty($mappings) || empty($tables)) { wp_send_json_error('Parâmetros inválidos.'); } // Expande os mapeamentos para cobrir variações de formato $mappings = sur_expand_mappings($mappings, $exact); global $wpdb; $from_urls = array_column($mappings, 'from'); // Mapa de substituição para strtr(): troca em PASSAGEM ÚNICA, casando a // chave mais longa primeiro e SEM reprocessar o texto já inserido. Isso // evita a corrupção em cascata do str_replace sequencial (ex.: uma regra // curta comendo o "//" de uma URL recém-inserida por outra regra). $replace_pairs = []; foreach ($mappings as $m) { if ($m['from'] !== '' && $m['from'] !== $m['to']) { $replace_pairs[$m['from']] = $m['to']; } } $sources = sur_get_table_sources($tables, $from_urls); $table_keys = array_keys($sources); if (! $table_key || ! isset($sources[$table_key])) { $table_key = $table_keys[0]; $offset = 0; } $src = $sources[$table_key]; // wp_options pode conter blobs serializados muito grandes e objetos // problemáticos. Processamos poucas linhas por requisição para limitar // o pico de memória (mais round-trips, porém estável). A paginação // continua correta porque o "done" compara com este mesmo $batch. if ($table_key === 'options') { $batch = min($batch, 5); } // IMPORTANTE: não usar $wpdb->prepare aqui. O select_sql do wp_options // contém '%' literais (em '%\_transient\_%') que o prepare trataria como // placeholders, corrompendo a query e gerando erro 500. $batch e $offset // já são inteiros (intval acima), então é seguro injetá-los via sprintf %d. $select_sql = str_replace( 'LIMIT %d OFFSET %d', sprintf('LIMIT %d OFFSET %d', $batch, $offset), $src['select_sql'] ); $rows = $wpdb->get_results($select_sql, ARRAY_A); $log_entries = []; // Marcador de versão: confirma que o código ATUAL está rodando (e não uma // versão antiga em cache do OPcache). Aparece uma vez, no início do lote. if ($table_key === $table_keys[0] && $offset === 0) { $log_entries[] = ['msg' => '[MOTOR v' . SUR_VERSION . '] Processamento resiliente ativo.', 'changed' => false]; } foreach ($rows as $row) { $original_raw = $row['record_value']; // Registra o ponto atual para o handler de erro fatal (acima). $GLOBALS['sur_ctx'] = ['table' => $src['label'], 'record_id' => $row['record_id']]; // Otimização: se o valor bruto não contém nenhum domínio mapeado, // pula sem desserializar/reserializar (a maioria das linhas cai aqui). if (strpos($original_raw, 'http') === false && strpos($original_raw, '/') === false) { continue; } // ── DESSERIALIZAÇÃO SEGURA ───────────────────────────────── // maybe_unserialize → editar estrutura PHP → maybe_serialize // Recalcula automaticamente os tamanhos s:N em dados serializados, // evitando corrupção de dados do ACF, Elementor etc. // // try/catch(\Throwable): alguns valores (ex.: objetos com Closures ou // recursos não serializáveis, comuns em wp_options) fazem o // maybe_serialize/maybe_unserialize lançar Error/Exception. Sem isto, // UMA linha ruim derruba o lote inteiro com erro 500. Aqui registramos // e pulamos a linha, deixando o processamento continuar. try { $unserialized = maybe_unserialize($original_raw); $replaced = sur_recursive_replace($replace_pairs, $unserialized); $new_raw = maybe_serialize($replaced); } catch (\Throwable $e) { $log_entries[] = [ 'msg' => sprintf('[IGNORADO] %s id=%s: %s', $src['label'], $row['record_id'], $e->getMessage()), 'changed' => false, ]; continue; } if ($new_raw === $original_raw) { continue; } $log_entries[] = [ 'msg' => sprintf('[%s] id=%s | %d ocorrência(s)%s', $src['label'], $row['record_id'], sur_count_changes($mappings, $original_raw), $dry_run ? ' (simulação)' : '' ), 'changed' => true, ]; if ($dry_run) { continue; } $result = $wpdb->update( $src['table'], [$src['value_col'] => $new_raw], [$src['id_col'] => $row['record_id']], ['%s'], ['%d'] ); if (false === $result) { $log_entries[] = ['msg' => '[ERRO BD] id=' . $row['record_id'] . ': ' . $wpdb->last_error, 'changed' => false]; } } $processed_count = count($rows); $next_offset = $offset + $processed_count; $current_idx = (int) array_search($table_key, $table_keys, true); $this_table_done = ($processed_count < $batch); $next_table_key = $table_key; $done = false; if ($this_table_done) { if ($current_idx < count($table_keys) - 1) { $next_table_key = $table_keys[$current_idx + 1]; $next_offset = 0; $log_entries[] = ['msg' => '── Concluída: ' . $src['label'] . ' ──', 'changed' => false]; } else { $done = true; } } $elementor_cleared = false; if ($done && ! $dry_run) { if (class_exists('\Elementor\Plugin') && isset(\Elementor\Plugin::$instance->files_manager)) { \Elementor\Plugin::$instance->files_manager->clear_cache(); $elementor_cleared = true; } } wp_send_json_success([ 'processed_in_batch' => $processed_count, 'next_table_key' => $next_table_key, 'next_offset' => $next_offset, 'current_table' => $src['label'], 'done' => $done, 'log' => $log_entries, 'elementor_cleared' => $elementor_cleared, ]); } // ============================================================================= // SUBSTITUIÇÃO RECURSIVA EM ESTRUTURAS DESSERIALIZADAS // ============================================================================= function sur_recursive_replace(array $pairs, $data, int $depth = 0) { // Proteção contra recursão profunda / referências circulares em dados // serializados (evita estouro de pilha / esgotamento de memória → 500). if ($depth > 60 || empty($pairs)) { return $data; } if (is_string($data)) { // strtr() faz a substituição em PASSAGEM ÚNICA: casa a chave mais longa // primeiro e NÃO reprocessa o texto recém-inserido. Isso evita a // corrupção em cascata do str_replace sequencial (ex.: comer o "//" de // uma URL que outra regra acabou de inserir). return strtr($data, $pairs); } if (is_array($data)) { foreach ($data as $key => $value) { $data[$key] = sur_recursive_replace($pairs, $value, $depth + 1); } return $data; } if (is_object($data)) { foreach (get_object_vars($data) as $prop => $value) { $data->$prop = sur_recursive_replace($pairs, $value, $depth + 1); } return $data; } return $data; } function sur_count_changes(array $mappings, string $raw): int { $count = 0; foreach ($mappings as $map) { $count += substr_count($raw, $map['from']); } return $count; } // ============================================================================= // AJAX: HEALTH CHECK DE URLs // ============================================================================= add_action('wp_ajax_sur_health_check', 'sur_ajax_health_check'); function sur_ajax_health_check() { check_ajax_referer('sur_health_check', '_wpnonce'); if (! current_user_can('manage_options')) { wp_send_json_error('Permissão negada.'); } $urls = json_decode(stripslashes(isset($_POST['urls']) ? $_POST['urls'] : '[]'), true); $results = []; foreach ($urls as $url) { if (! filter_var($url, FILTER_VALIDATE_URL)) { $results[] = ['url' => $url, 'code' => 'URL inválida']; continue; } $response = wp_remote_head($url, ['timeout' => 10, 'redirection' => 3, 'sslverify' => false, 'user-agent' => 'WordPress SEO URL Replacer/' . SUR_VERSION]); if (is_wp_error($response)) { $results[] = ['url' => $url, 'code' => 'Erro: ' . $response->get_error_message()]; } else { $results[] = ['url' => $url, 'code' => wp_remote_retrieve_response_code($response)]; } } wp_send_json_success($results); }
Save File
Cancel