Plugin Directory

Changeset 3436160


Ignore:
Timestamp:
01/09/2026 05:17:57 PM (3 months ago)
Author:
andre.luiz
Message:

Versao 2.7.2 com correcao de logica de datas do Analytics

Location:
digi-report/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • digi-report/trunk/digi-report.php

    r3436145 r3436160  
    33Plugin Name: Digi Report
    44Description: A plugin that generates and sends WordPress maintenance reports via email (Integrated with Independent Analytics).
    5 Version: 2.7.1
     5Version: 2.7.2
    66Author: DigiPerforma - Marketing Digital [digiperforma.com.br]
    77License: GPLv2 or later
     
    2424
    2525function meu_plugin_relatorios_menu() {
    26     // ALTERAÇÃO: Nome do menu na sidebar mudado para "DigiReport"
     26    // Força o nome "DigiReport"
    2727    add_options_page('Configurações do Relatório', 'DigiReport', 'manage_options', 'meu-plugin-relatorios', 'meu_plugin_relatorios_pagina');
    2828}
     
    4141    }
    4242
    43     // Dados Salvos
    4443    $email_destino = get_option('meu_plugin_relatorios_email');
    4544    $email_opcional = get_option('meu_plugin_relatorios_email_opcional');
     
    4746    $mensagem_mes = get_option('meu_plugin_relatorios_mensagem', '');
    4847
    49     // --- COLETA DE DADOS (Restaurada para 5 itens) ---
     48    // --- COLETA DE DADOS ---
    5049    global $wpdb;
    51     $one_month_ago = gmdate('Y-m-d H:i:s', strtotime('-1 month', current_time('timestamp')));
     50   
     51    // Mudança: Agora pegamos dados dos últimos 30 dias para garantir que apareça algo
     52    $start_date = date('Y-m-d H:i:s', strtotime('-30 days'));
    5253
    5354    // 1. Criados
    54     $args_criados = array('post_type' => array('post', 'page'), 'post_status' => 'publish', 'date_query' => array(array('after' => '1 month ago')), 'fields' => 'ids');
     55    $args_criados = array('post_type' => array('post', 'page'), 'post_status' => 'publish', 'date_query' => array(array('after' => '30 days ago')), 'fields' => 'ids');
    5556    $posts_criados = (new WP_Query($args_criados))->found_posts ?: '0';
    5657
    57     // 2. Atualizados (Conteúdo)
    58     $posts_atualizados = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type IN ('post', 'page') AND post_status = 'publish' AND post_modified > post_date AND post_modified >= %s", $one_month_ago));
     58    // 2. Atualizados
     59    $posts_atualizados = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type IN ('post', 'page') AND post_status = 'publish' AND post_modified > post_date AND post_modified >= %s", $start_date));
    5960    $posts_atualizados_texto = ($posts_atualizados > 0) ? $posts_atualizados : '0';
    6061
    61     // 3. Plugins
    6262    $plugins_atualizados = count(get_option('meu_plugin_relatorios_plugins_atualizados', array()));
    63 
    64     // 4. WordPress Core
    6563    $wp_core_updates = count(get_option('meu_plugin_relatorios_wp_atualizacoes', array()));
    6664
    67     // 5. Spam
    6865    $spam_count = wp_count_comments();
    6966    $spam_bloqueado = isset($spam_count->spam) ? $spam_count->spam : 0;
    7067
    71     // Coleta de Dados do Independent Analytics
    7268    $analytics = digi_report_get_analytics_data();
    7369
     
    8884        <h1 style="text-align: center; color: #444;">Painel DigiReport</h1>
    8985       
    90         <h2 class="digi-section-title">Manutenção & Segurança</h2>
     86        <h2 class="digi-section-title">Manutenção (Últimos 30 dias)</h2>
    9187        <div class="digi-card-row">
    9288            <div class="digi-card"><h3>Posts/Páginas Criados</h3><p><?php echo esc_html($posts_criados); ?></p></div>
     
    9894
    9995        <?php if ($analytics['active']): ?>
    100         <h2 class="digi-section-title">Performance (Independent Analytics)</h2>
     96        <h2 class="digi-section-title">Tráfego (Últimos 30 dias)</h2>
    10197        <div class="digi-card-row">
    10298            <div class="digi-card"><h3>Visualizações</h3><p><?php echo esc_html($analytics['views']); ?></p></div>
     
    105101        <div class="digi-card-row">
    106102            <div class="digi-card" style="text-align: left;">
    107                 <h3>Top 3 Páginas</h3>
     103                <h3>Top Páginas</h3>
    108104                <ul style="margin:0; padding-left: 20px; font-size: 0.9em; color: #555;">
    109105                    <?php foreach($analytics['top_pages'] as $page) echo "<li>" . esc_html($page['name']) . " <strong>(" . esc_html($page['views']) . ")</strong></li>"; ?>
     
    111107            </div>
    112108            <div class="digi-card" style="text-align: left;">
    113                 <h3>Top 3 Cidades</h3>
     109                <h3>Top Cidades</h3>
    114110                <ul style="margin:0; padding-left: 20px; font-size: 0.9em; color: #555;">
    115111                    <?php foreach($analytics['top_cities'] as $city) echo "<li>" . esc_html($city['city']) . " <strong>(" . esc_html($city['visitors']) . ")</strong></li>"; ?>
     
    118114        </div>
    119115        <?php else: ?>
    120             <div class="notice notice-warning inline"><p><strong>Atenção:</strong> O plugin "Independent Analytics" não foi detectado ou ainda não possui dados. Instale-o para ver métricas de tráfego aqui.</p></div>
     116            <div class="notice notice-warning inline"><p><strong>Status do Analytics:</strong> Não detectamos dados recentes. Certifique-se de que o plugin <em>Independent Analytics</em> está ativo e que o site teve visitas nos últimos 30 dias.</p></div>
    121117        <?php endif; ?>
    122118
     
    147143    global $wpdb;
    148144
    149     // ALTERAÇÃO: Verifica se a opção do Independent Analytics existe
    150     // Essa é a maneira mais segura de saber se o plugin está instalado
    151     $ia_version = get_option('ia_db_version');
    152    
    153     // Se a opção não existe, assume que o plugin não está instalado
    154     if (!$ia_version) {
     145    // Tabelas do Independent Analytics
     146    $table_views = $wpdb->prefix . 'ia_views';
     147    $table_sessions = $wpdb->prefix . 'ia_sessions';
     148
     149    // AJUSTE CRÍTICO: Usa 'Last 30 days' ao invés de 'Last Month'
     150    // Isso garante que se você instalou hoje, já aparece dados de hoje.
     151    $start_date = date('Y-m-d', strtotime('-30 days'));
     152    $end_date   = date('Y-m-d');
     153
     154    // Verifica se a tabela existe de forma bruta (mais garantido)
     155    if ($wpdb->get_var("SHOW TABLES LIKE '$table_views'") != $table_views) {
    155156        return array('active' => false);
    156157    }
    157158
    158     // Tabelas
    159     $table_views = $wpdb->prefix . 'ia_views';
    160     $table_sessions = $wpdb->prefix . 'ia_sessions';
    161 
    162     // Período: Mês Passado
    163     $first_day = date('Y-m-01', strtotime('last month'));
    164     $last_day  = date('Y-m-t', strtotime('last month'));
    165 
    166     // Tenta buscar os dados. Se der erro SQL (tabela não existe), captura silenciavelmente.
    167     $views = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table_views WHERE `date` BETWEEN %s AND %s", $first_day, $last_day));
    168    
    169     if ($views === null) {
    170         return array('active' => false); // Tabela não encontrada
    171     }
    172 
    173     $visitors = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table_sessions WHERE `date` BETWEEN %s AND %s", $first_day, $last_day));
     159    // Tenta buscar visualizações
     160    $views = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table_views WHERE `date` BETWEEN %s AND %s", $start_date, $end_date));
     161   
     162    // Se retornou NULL ou zero, pode ser que não tenha dados, mas a tabela existe.
     163    // Vamos considerar ativo se a tabela existe, mesmo que views seja 0.
     164   
     165    $visitors = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table_sessions WHERE `date` BETWEEN %s AND %s", $start_date, $end_date));
    174166
    175167    $top_pages = $wpdb->get_results($wpdb->prepare(
    176168        "SELECT page_path as name, COUNT(*) as views FROM $table_views WHERE `date` BETWEEN %s AND %s GROUP BY page_path ORDER BY views DESC LIMIT 3",
    177         $first_day, $last_day
     169        $start_date, $end_date
    178170    ), ARRAY_A);
    179171
    180172    $top_cities = $wpdb->get_results($wpdb->prepare(
    181173        "SELECT city, COUNT(*) as visitors FROM $table_sessions WHERE `date` BETWEEN %s AND %s AND city != '' GROUP BY city ORDER BY visitors DESC LIMIT 3",
    182         $first_day, $last_day
     174        $start_date, $end_date
    183175    ), ARRAY_A);
    184176
     
    193185
    194186// =========================================================
    195 // 3. ENVIO DE E-MAIL (TEMPLATE ATUALIZADO)
     187// 3. ENVIO DE E-MAIL
    196188// =========================================================
    197189function meu_plugin_relatorios_enviar() {
     
    202194
    203195    $msg_raw = get_option('meu_plugin_relatorios_mensagem', '');
    204     $msg_final = empty($msg_raw) ? "Mantivemos o monitoramento ativo. Confira abaixo os resultados de tráfego e as atualizações de segurança realizadas no período." : nl2br(esc_html($msg_raw));
    205 
    206     // COLETA PARA E-MAIL (5 ITENS)
     196    $msg_final = empty($msg_raw) ? "Mantivemos o monitoramento ativo. Confira abaixo os resultados de tráfego (últimos 30 dias) e as atualizações de segurança." : nl2br(esc_html($msg_raw));
     197
     198    // DADOS PARA E-MAIL (Mesma lógica de 30 dias)
    207199    global $wpdb;
    208     $one_month_ago = gmdate('Y-m-d H:i:s', strtotime('-1 month', current_time('timestamp')));
    209    
    210     // Criados
    211     $args_criados = array('post_type' => array('post', 'page'), 'post_status' => 'publish', 'date_query' => array(array('after' => '1 month ago')), 'fields' => 'ids');
     200    $start_date = date('Y-m-d H:i:s', strtotime('-30 days'));
     201
     202    $args_criados = array('post_type' => array('post', 'page'), 'post_status' => 'publish', 'date_query' => array(array('after' => '30 days ago')), 'fields' => 'ids');
    212203    $posts_criados_txt = (new WP_Query($args_criados))->found_posts ?: '-';
    213204   
    214     // Atualizados
    215     $posts_atualizados_num = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type IN ('post', 'page') AND post_status = 'publish' AND post_modified > post_date AND post_modified >= %s", $one_month_ago));
     205    $posts_atualizados_num = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type IN ('post', 'page') AND post_status = 'publish' AND post_modified > post_date AND post_modified >= %s", $start_date));
    216206    $posts_atualizados_txt = ($posts_atualizados_num > 0) ? $posts_atualizados_num : '-';
    217207
    218     // Plugins
    219208    $plugins_txt = count(get_option('meu_plugin_relatorios_plugins_atualizados', array())) ?: '-';
    220    
    221     // WP Core
    222209    $wp_core_txt = count(get_option('meu_plugin_relatorios_wp_atualizacoes', array())) ?: '-';
    223    
    224     // Spam
    225210    $spam_count = wp_count_comments();
    226211    $spam_txt = isset($spam_count->spam) ? $spam_count->spam : '-';
    227212
    228     // Analytics
    229213    $analytics = digi_report_get_analytics_data();
    230214   
     
    240224
    241225        $html_analytics = '
    242         <h3 style="text-align: center; margin-top: 30px; color: #f4ab1d; text-transform: uppercase;">Performance de Acesso</h3>
     226        <h3 style="text-align: center; margin-top: 30px; color: #f4ab1d; text-transform: uppercase;">Performance (30 Dias)</h3>
    243227        <table style="width: 100%; border-collapse: collapse;">
    244228            <tr>
     
    321305    }
    322306}
    323 
    324 // Ganchos
     307// Ganchos... (resto do arquivo igual)
    325308function meu_plugin_relatorios_agendar() { if (!wp_next_scheduled('meu_plugin_relatorios_gancho')) wp_schedule_event(time(), 'daily', 'meu_plugin_relatorios_gancho'); }
    326309add_action('wp', 'meu_plugin_relatorios_agendar');
     
    328311add_action('meu_plugin_relatorios_gancho', 'meu_plugin_relatorios_verifica_dia');
    329312register_deactivation_hook(__FILE__, function() { wp_unschedule_event(wp_next_scheduled('meu_plugin_relatorios_gancho'), 'meu_plugin_relatorios_gancho'); });
    330 
    331 function meu_plugin_relatorios_teste_envio() {
    332     if (isset($_POST['meu_plugin_relatorios_teste']) && check_admin_referer('meu_plugin_relatorios_teste', 'meu_plugin_relatorios_teste_nonce')) {
    333         meu_plugin_relatorios_enviar();
    334         add_action('admin_notices', function() { echo '<div class="notice notice-success is-dismissible"><p>Relatório de teste enviado com sucesso!</p></div>'; });
    335     }
    336 }
     313function meu_plugin_relatorios_teste_envio() { if (isset($_POST['meu_plugin_relatorios_teste']) && check_admin_referer('meu_plugin_relatorios_teste', 'meu_plugin_relatorios_teste_nonce')) { meu_plugin_relatorios_enviar(); add_action('admin_notices', function() { echo '<div class="notice notice-success is-dismissible"><p>Relatório de teste enviado com sucesso!</p></div>'; }); } }
    337314add_action('admin_init', 'meu_plugin_relatorios_teste_envio');
    338 
    339 function meu_plugin_monitora_updates($upgrader, $options) {
    340     if ($options['action'] === 'update' && $options['type'] === 'plugin' && !empty($options['plugins'])) {
    341         $atual = get_option('meu_plugin_relatorios_plugins_atualizados', array());
    342         foreach ($options['plugins'] as $f) { $d = get_plugin_data(WP_PLUGIN_DIR.'/'.$f); $atual[] = array('nome' => $d['Name'], 'data' => gmdate('Y-m-d H:i:s')); }
    343         update_option('meu_plugin_relatorios_plugins_atualizados', $atual);
    344     }
    345     if ($options['action'] === 'update' && $options['type'] === 'core') {
    346         $atual = get_option('meu_plugin_relatorios_wp_atualizacoes', array());
    347         $atual[] = gmdate('Y-m-d H:i:s');
    348         update_option('meu_plugin_relatorios_wp_atualizacoes', $atual);
    349     }
    350 }
     315function meu_plugin_monitora_updates($upgrader, $options) { if ($options['action'] === 'update' && $options['type'] === 'plugin' && !empty($options['plugins'])) { $atual = get_option('meu_plugin_relatorios_plugins_atualizados', array()); foreach ($options['plugins'] as $f) { $d = get_plugin_data(WP_PLUGIN_DIR.'/'.$f); $atual[] = array('nome' => $d['Name'], 'data' => gmdate('Y-m-d H:i:s')); } update_option('meu_plugin_relatorios_plugins_atualizados', $atual); } if ($options['action'] === 'update' && $options['type'] === 'core') { $atual = get_option('meu_plugin_relatorios_wp_atualizacoes', array()); $atual[] = gmdate('Y-m-d H:i:s'); update_option('meu_plugin_relatorios_wp_atualizacoes', $atual); } }
    351316add_action('upgrader_process_complete', 'meu_plugin_monitora_updates', 10, 2);
    352317?>
  • digi-report/trunk/readme.txt

    r3436145 r3436160  
    44Requires at least: 5.0
    55Tested up to: 6.8
    6 Stable tag: 2.7.1
     6Stable tag: 2.7.2
    77Requires PHP: 7.2
    88License: GPLv2 or later
Note: See TracChangeset for help on using the changeset viewer.