wordpress: controllare lo stato di aggiornamento del core e dei plugin

Dovendo controllare spesso alcuni siti web con wordpress installato ho realizzato uno script PHP da caricare nella cartella dove risiede wordpress (in particolare il file wp-load.php) per poi poterlo richiamare via web con un token di sicurezza.

Questo lo script:

<?php
/**
 * WordPress Maintenance, Update & CVE Security Checker Utility
 *
 * Formati disponibili (parametro format):
 *   - text : output tabellare/leggibile da terminale (Default in CLI)
 *   - html : interfaccia grafica visuale (Default via Web)
 *   - json : output dati strutturato
 *
 * Parametri accettati:
 *   - token     : Chiave di sicurezza per chiamate Web (es. ?token=MODIFICA_QUESTO_TOKEN_SICURO)
 *   - format    : 'text', 'html', 'json'
 *   - action    : 'status' (default, sola lettura) oppure 'update'
 *   - target    : Componente/i da aggiornare con action=update:
 *                 'all' (tutto), 'core', 'plugins', 'themes', o slug specifico (es. 'woocommerce/woocommerce.php')
 *   - check_cve : 1 (default) oppure 0 per disabilitare il controllo vulnerabilità
 *
 * Esempi CLI:
 *   php wp-manager.php                          # Default CLI: testo formattato con elenco CVE
 *   php wp-manager.php --action=update --target=plugins
 *   php wp-manager.php --action=update --target=all
 *   php wp-manager.php --format=json
 *
 * Esempi Web:
 *   https://tuosito.com/wp-manager.php?token=SEGRETO               # Default Web: HTML con alert CVE
 *   https://tuosito.com/wp-manager.php?token=SEGRETO&format=json   # JSON API per monitoraggio
 */

// --------------------------------------------------------------------------
// 1. Configurazione di Sicurezza e Risorse
// --------------------------------------------------------------------------
define('ACCESS_TOKEN', 'MODIFICA_QUESTO_TOKEN_SICURO'); // Modifica con una password/token sicura

@set_time_limit(900); // 15 minuti per download, aggiornamenti e check vulnerabilità
@ini_set('memory_limit', '512M');

$is_cli = (php_sapi_name() === 'cli' || defined('STDIN'));

// Parsing parametri (CLI o GET)
$params = [];
if ($is_cli) {
    $options = getopt('', ['token::', 'format::', 'action::', 'target::', 'check_cve::']);
    $params['format']    = strtolower($options['format'] ?? 'text');
    $params['action']    = strtolower($options['action'] ?? 'status');
    $params['target']    = $options['target'] ?? 'all';
    $params['check_cve'] = isset($options['check_cve']) ? (bool)$options['check_cve'] : true;
} else {
    if (!isset($_GET['token']) || $_GET['token'] !== ACCESS_TOKEN) {
        http_response_code(403);
        die("Accesso negato: token non valido o assente.\n");
    }
    $params['format']    = strtolower($_GET['format'] ?? 'html');
    $params['action']    = strtolower($_GET['action'] ?? 'status');
    $params['target']    = $_GET['target'] ?? 'all';
    $params['check_cve'] = isset($_GET['check_cve']) ? (bool)$_GET['check_cve'] : true;
}

// --------------------------------------------------------------------------
// 2. Caricamento Ambiente WordPress
// --------------------------------------------------------------------------
$wp_load_path = __DIR__ . '/wp-load.php';
if (!file_exists($wp_load_path)) {
    die("Errore: impossibile trovare 'wp-load.php'. Posiziona lo script nella root di WordPress.\n");
}
require_once $wp_load_path;

// Forzatura metodo filesystem diretto per evitare blocchi FTP
if (!defined('FS_METHOD')) {
    define('FS_METHOD', 'direct');
}

require_once ABSPATH . 'wp-admin/includes/admin.php';
require_once ABSPATH . 'wp-admin/includes/plugin.php';
require_once ABSPATH . 'wp-admin/includes/theme.php';
require_once ABSPATH . 'wp-admin/includes/update.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/misc.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';

// In ambiente CLI assegna il contesto amministratore per soddisfare i controlli di permessi
if ($is_cli && !is_user_logged_in()) {
    $admins = get_users(['role' => 'administrator', 'number' => 1]);
    if (!empty($admins)) {
        wp_set_current_user($admins[0]->ID);
    }
}

// Skin silenziosa per gli Upgrader nativi di WordPress
class Silent_Upgrader_Skin extends WP_Upgrader_Skin {
    public $messages = [];
    public function header() {}
    public function footer() {}
    public function feedback($string, ...$args) {
        if (!empty($args)) {
            $string = vsprintf($string, $args);
        }
        $this->messages[] = trim(strip_tags($string));
    }
    public function error($errors) {
        if (is_wp_error($errors)) {
            $this->messages[] = '[ERRORE] ' . $errors->get_error_message();
        } elseif (is_string($errors)) {
            $this->messages[] = '[ERRORE] ' . $errors;
        }
    }
}

// --------------------------------------------------------------------------
// 3. Helper per il Calcolo e Filtro Vulnerabilità
// --------------------------------------------------------------------------

/**
 * Verifica se la versione installata ricade nell'intervallo vulnerabile dichiarato
 */
function is_version_vulnerable($installed_ver, $vuln) {
    if (empty($installed_ver) || $installed_ver === 'N/D') {
        return false;
    }

    $clean_installed = preg_replace('/^v/i', '', trim($installed_ver));

    // Se esiste 'fixed_in' valido e la versione installata è >= alla versione corretta, non è vulnerabile
    if (!empty($vuln['fixed_in']) && preg_match('/^\d+(\.\d+)*/', $vuln['fixed_in'], $fix_match)) {
        if (version_compare($clean_installed, $fix_match[0], '>=')) {
            return false;
        }
    }

    $map_op = function($op) {
        $op = strtolower(trim((string)$op));
        switch ($op) {
            case 'le': return '<=';
            case 'lt': return '<';
            case 'ge': return '>=';
            case 'gt': return '>';
            case 'eq': return '==';
            case 'ne': return '!=';
            default:   return in_array($op, ['<=', '<', '>=', '>', '==', '!=', '='], true) ? ($op === '=' ? '==' : $op) : '<=';
        }
    };

    $op_data = $vuln['operator'] ?? [];

    // Struttura 1: Range min/max (min_version/max_version)
    if (is_array($op_data) && (!empty($op_data['min_version']) || !empty($op_data['max_version']))) {
        $min_ok = true;
        $max_ok = true;

        if (!empty($op_data['min_version'])) {
            $min_op = $map_op($op_data['min_operator'] ?? 'ge');
            $min_ver = preg_replace('/^v/i', '', trim($op_data['min_version']));
            $min_ok = version_compare($clean_installed, $min_ver, $min_op);
        }

        if (!empty($op_data['max_version'])) {
            $max_op = $map_op($op_data['max_operator'] ?? 'le');
            $max_ver = preg_replace('/^v/i', '', trim($op_data['max_version']));
            $max_ok = version_compare($clean_installed, $max_ver, $max_op);
        }

        return ($min_ok && $max_ok);
    }

    // Struttura 2: Operatore singolo con target version
    if (is_array($op_data) && !empty($op_data['version'])) {
        $single_op = $map_op($op_data['operator'] ?? 'le');
        $target_ver = preg_replace('/^v/i', '', trim($op_data['version']));
        return version_compare($clean_installed, $target_ver, $single_op);
    }

    // Struttura 3: Operatore o versione testuale (es. "<= 1.2.3")
    $text_check = is_string($op_data) ? $op_data : ($vuln['version_affected'] ?? '');
    if (!empty($text_check) && preg_match('/^(<=|<|>=|>|==|=)?\s*([0-9\.]+.*)$/', trim($text_check), $m)) {
        $op = !empty($m) ? $map_op($m) : '<=';
        return version_compare($clean_installed, trim($m), $op);
    }

    // In assenza di match certo, evitare falsi allarmi
    return false;
}

function fetch_component_cves($type, $slug, $installed_version) {
    if (empty($slug) || $installed_version === 'N/D' || empty($installed_version)) {
        return [];
    }

    $clean_slug = $slug;
    if ($type === 'plugin' && strpos($slug, '/') !== false) {
        $clean_slug = explode('/', $slug)[0];
    }

    // Prefisso di cache incrementato per invalidare i transient precedenti con logica non filtrata
    $cache_key = 'wp_cve_v2_' . md5($type . '_' . $clean_slug . '_' . $installed_version);
    $cached = get_transient($cache_key);
    if ($cached !== false) {
        return $cached;
    }

    // Endpoint WPVulnerability
    $endpoint = '';
    if ($type === 'core') {
        $endpoint = 'https://www.wpvulnerability.net/core/' . urlencode($installed_version) . '/';
    } elseif ($type === 'plugin') {
        $endpoint = 'https://www.wpvulnerability.net/plugin/' . urlencode($clean_slug) . '/';
    } elseif ($type === 'theme') {
        $endpoint = 'https://www.wpvulnerability.net/theme/' . urlencode($clean_slug) . '/';
    }

    $cves = [];
    $response = wp_remote_get($endpoint, [
        'timeout' => 6,
        'headers' => ['Accept' => 'application/json', 'User-Agent' => 'WordPress-Vulnerability-Audit/1.0']
    ]);

    if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        if (!empty($data['data']['vulnerability'])) {
            foreach ($data['data']['vulnerability'] as $vuln) {
                $is_vulnerable = false;

                if ($type === 'core') {
                    // Per il core l'endpoint filtra per versione, ma scartiamo le vulnerabilità già risolte
                    if (!empty($vuln['fixed_in']) && preg_match('/^\d+(\.\d+)*/', $vuln['fixed_in'], $fix_match)) {
                        $is_vulnerable = version_compare($installed_version, $fix_match[0], '<');
                    } else {
                        $is_vulnerable = is_version_vulnerable($installed_version, $vuln) ?: true;
                    }
                } else {
                    // Per plugin e temi filtriamo rigorosamente in base al range dichiarato dall'API
                    $is_vulnerable = is_version_vulnerable($installed_version, $vuln);
                }

                if ($is_vulnerable) {
                    $cve_id = !empty($vuln['cve']) ? $vuln['cve'] : ($vuln['source'][0]['id'] ?? 'N/A');
                    $cves[] = [
                        'cve'      => $cve_id,
                        'name'     => $vuln['name'] ?? 'Vulnerabilità di sicurezza non denominata',
                        'severity' => $vuln['severity'] ?? ($vuln['impact']['cvss']['severity'] ?? 'Medium'),
                        'score'    => $vuln['impact']['cvss']['score'] ?? null,
                        'fixed_in' => $vuln['fixed_in'] ?? ($vuln['operator']['max_version'] ?? ($vuln['operator']['version'] ?? 'Non specificata')),
                        'link'     => !empty($vuln['source'][0]['link']) ? $vuln['source'][0]['link'] : "https://nvd.nist.gov/vuln/detail/{$cve_id}",
                    ];
                }
            }
        }
    }

    set_transient($cache_key, $cves, 6 * HOUR_IN_SECONDS);
    return $cves;
}

// --------------------------------------------------------------------------
// 4. Forzatura Check Aggiornamenti
// --------------------------------------------------------------------------
wp_version_check();
wp_update_plugins();
wp_update_themes();

// --------------------------------------------------------------------------
// 5. Esecuzione Aggiornamenti (se richiesta action=update)
// --------------------------------------------------------------------------
$update_results = [];

if ($params['action'] === 'update') {
    $target = $params['target'];

    // Inizializza filesystem WordPress
    $creds = request_filesystem_credentials('', '', false, false, null);
    if (!WP_Filesystem($creds)) {
        $update_results['filesystem_error'] = "Impossibile inizializzare WP_Filesystem.";
    } else {
        // A. Aggiornamento WordPress Core
        if (in_array($target, ['all', 'core'], true)) {
            $core_updates = get_core_updates();
            if (!empty($core_updates) && $core_updates[0]->response === 'upgrade') {
                $skin = new Silent_Upgrader_Skin();
                $upgrader = new Core_Upgrader($skin);
                $res = $upgrader->upgrade($core_updates[0]);
                $update_results['core'] = [
                    'target_version' => $core_updates[0]->current,
                    'success'        => !is_wp_error($res) && $res !== false,
                    'messages'       => $skin->messages,
                    'error'          => is_wp_error($res) ? $res->get_error_message() : null
                ];
            } else {
                $update_results['core'] = [
                    'target_version' => null,
                    'success'        => true,
                    'messages'       => ['Il Core di WordPress è già aggiornato.']
                ];
            }
        }

        // B. Aggiornamento Plugin
        if ($target === 'all' || $target === 'plugins' || (strpos($target, '.php') !== false)) {
            $skin = new Silent_Upgrader_Skin();
            $upgrader = new Plugin_Upgrader($skin);
            $plugins_update = get_site_transient('update_plugins');

            if (!empty($plugins_update->response)) {
                $plugins_to_update = [];
                if ($target === 'all' || $target === 'plugins') {
                    $plugins_to_update = array_keys($plugins_update->response);
                } elseif (isset($plugins_update->response[$target])) {
                    $plugins_to_update = [$target];
                }

                if (!empty($plugins_to_update)) {
                    $res = $upgrader->bulk_upgrade($plugins_to_update);
                    $update_results['plugins'] = [
                        'updated'  => $plugins_to_update,
                        'result'   => $res,
                        'messages' => $skin->messages
                    ];
                } else {
                    $update_results['plugins'] = [
                        'updated'  => [],
                        'messages' => ['Nessun aggiornamento disponibile per il/i plugin specificato/i.']
                    ];
                }
            } else {
                $update_results['plugins'] = [
                    'updated'  => [],
                    'messages' => ['Tutti i plugin risultano già aggiornati.']
                ];
            }
        }

        // C. Aggiornamento Temi
        if (in_array($target, ['all', 'themes'], true) || (!in_array($target, ['all', 'core', 'plugins'], true) && strpos($target, '.php') === false)) {
            $skin = new Silent_Upgrader_Skin();
            $upgrader = new Theme_Upgrader($skin);
            $themes_update = get_site_transient('update_themes');

            if (!empty($themes_update->response)) {
                $themes_to_update = [];
                if ($target === 'all' || $target === 'themes') {
                    $themes_to_update = array_keys($themes_update->response);
                } elseif (isset($themes_update->response[$target])) {
                    $themes_to_update = [$target];
                }

                if (!empty($themes_to_update)) {
                    $res = $upgrader->bulk_upgrade($themes_to_update);
                    $update_results['themes'] = [
                        'updated'  => $themes_to_update,
                        'result'   => $res,
                        'messages' => $skin->messages
                    ];
                } else {
                    $update_results['themes'] = [
                        'updated'  => [],
                        'messages' => ['Nessun aggiornamento disponibile per il/i tema/i specificato/i.']
                    ];
                }
            } else {
                $update_results['themes'] = [
                    'updated'  => [],
                    'messages' => ['Tutti i temi risultano già aggiornati.']
                ];
            }
        }

        // Refresh post-upgrade
        wp_version_check();
        wp_update_plugins();
        wp_update_themes();
    }
}

// --------------------------------------------------------------------------
// 6. Raccolta Dati di Stato e Analisi CVE
// --------------------------------------------------------------------------
global $wp_version;

// Core
$core_updates = get_site_transient('update_core');
$latest_core_version = $wp_version;
$core_has_update = false;

if ($core_updates && !empty($core_updates->updates)) {
    foreach ($core_updates->updates as $update) {
        if (isset($update->response) && $update->response === 'upgrade') {
            $latest_core_version = $update->current;
            $core_has_update = true;
            break;
        }
    }
}
$core_cves = $params['check_cve'] ? fetch_component_cves('core', 'wordpress', $wp_version) : [];

// Plugin
$all_plugins = get_plugins();
$plugins_update = get_site_transient('update_plugins');
$plugin_report = [];

foreach ($all_plugins as $file => $data) {
    $cur_ver = $data['Version'] ?? 'N/D';
    $new_ver = $cur_ver;
    $has_update = false;

    if (isset($plugins_update->response[$file])) {
        $new_ver = $plugins_update->response[$file]->new_version ?? 'Sconosciuta';
        $has_update = true;
    }

    $cves = $params['check_cve'] ? fetch_component_cves('plugin', $file, $cur_ver) : [];

    $plugin_report[] = [
        'name'            => $data['Name'],
        'slug'            => $file,
        'active'          => is_plugin_active($file),
        'current_version' => $cur_ver,
        'latest_version'  => $new_ver,
        'has_update'      => $has_update,
        'cves'            => $cves,
    ];
}

// Temi
$all_themes = wp_get_themes();
$themes_update = get_site_transient('update_themes');
$theme_report = [];

foreach ($all_themes as $stylesheet => $theme_obj) {
    $cur_ver = $theme_obj->get('Version');
    $new_ver = $cur_ver;
    $has_update = false;

    if (isset($themes_update->response[$stylesheet])) {
        $new_ver = $themes_update->response[$stylesheet]['new_version'] ?? 'Sconosciuta';
        $has_update = true;
    }

    $cves = $params['check_cve'] ? fetch_component_cves('theme', $stylesheet, $cur_ver) : [];

    $theme_report[] = [
        'name'            => $theme_obj->get('Name'),
        'slug'            => $stylesheet,
        'active'          => (get_stylesheet() === $stylesheet),
        'current_version' => $cur_ver,
        'latest_version'  => $new_ver,
        'has_update'      => $has_update,
        'cves'            => $cves,
    ];
}

// --------------------------------------------------------------------------
// 7. Generazione Output: TEXT, JSON o HTML
// --------------------------------------------------------------------------
$data_payload = [
    'timestamp'      => current_time('mysql'),
    'site_url'       => home_url(),
    'action'         => $params['action'],
    'update_results' => $update_results,
    'core'           => [
        'current'    => $wp_version,
        'latest'     => $latest_core_version,
        'has_update' => $core_has_update,
        'cves'       => $core_cves,
    ],
    'plugins'        => $plugin_report,
    'themes'         => $theme_report,
];

// OUTPUT: JSON
if ($params['format'] === 'json') {
    if (!$is_cli) {
        header('Content-Type: application/json; charset=UTF-8');
    }
    echo json_encode($data_payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n";
    exit;
}

// OUTPUT: TEXT (Default CLI o esplicito)
if ($params['format'] === 'text') {
    if (!$is_cli) {
        header('Content-Type: text/plain; charset=UTF-8');
    }

    $sep = str_repeat("=", 80) . "\n";
    $subsep = str_repeat("-", 80) . "\n";

    echo $sep;
    echo "  STATO WORDPRESS, AGGIORNAMENTI & REPORT SICUREZZA (CVE)\n";
    echo "  Sito: " . home_url() . " | Data: " . current_time('mysql') . "\n";
    echo $sep . "\n";

    if (!empty($update_results)) {
        echo "[!] RISULTATI ESECUZIONE AGGIORNAMENTI:\n";
        print_r($update_results);
        echo "\n" . $sep . "\n";
    }

    // 1. Core
    echo "1. WORDPRESS CORE\n";
    echo $subsep;
    echo "   Versione Corrente   : " . $wp_version . "\n";
    echo "   Versione Repository : " . $latest_core_version . "\n";
    echo "   Stato               : " . ($core_has_update ? "[!] DA AGGIORNARE" : "[OK] AGGIORNATO") . "\n";
    if (!empty($core_cves)) {
        echo "   [ALLERTA] Rilevate " . count($core_cves) . " vulnerabilità CVE sul Core installato:\n";
        foreach ($core_cves as $cve) {
            echo "     - " . $cve['cve'] . " (" . $cve['severity'] . "): " . $cve['name'] . "\n";
        }
    } else {
        echo "   Vulnerabilità CVE   : Nessuna nota per questa versione.\n";
    }
    echo "\n";

    // 2. Plugins
    echo "2. PLUGIN (" . count($plugin_report) . " installati)\n";
    echo $subsep;
    printf("   %-28s | %-9s | %-9s | %-10s | %-12s\n", "Nome Plugin", "Inst.", "Nuova", "Stato", "CVE Rilevati");
    echo $subsep;
    foreach ($plugin_report as $p) {
        $short_name = (mb_strlen($p['name']) > 26) ? mb_substr($p['name'], 0, 23) . '...' : $p['name'];
        $status_label = $p['has_update'] ? "UPGRADE" : "OK";
        if (!$p['active']) {
            $status_label .= " (Off)";
        }
        $cve_count = count($p['cves']);
        $cve_label = ($cve_count > 0) ? "[!] {$cve_count} CVE" : "0";

        printf(
            "   %-28s | %-9s | %-9s | %-10s | %-12s\n",
            $short_name,
            $p['current_version'],
            $p['latest_version'],
            $status_label,
            $cve_label
        );

        if ($cve_count > 0) {
            foreach ($p['cves'] as $cve) {
                echo "       ↳ " . $cve['cve'] . " [" . $cve['severity'] . "] " . $cve['name'] . "\n";
            }
        }
    }
    echo "\n";

    // 3. Temi
    echo "3. TEMI / TEMPLATE (" . count($theme_report) . " installati)\n";
    echo $subsep;
    printf("   %-28s | %-9s | %-9s | %-10s | %-12s\n", "Nome Tema", "Inst.", "Nuova", "Stato", "CVE Rilevati");
    echo $subsep;
    foreach ($theme_report as $t) {
        $short_name = (mb_strlen($t['name']) > 26) ? mb_substr($t['name'], 0, 23) . '...' : $t['name'];
        $status_label = $t['has_update'] ? "UPGRADE" : "OK";
        if ($t['active']) {
            $status_label .= " [ATTIVO]";
        }
        $cve_count = count($t['cves']);
        $cve_label = ($cve_count > 0) ? "[!] {$cve_count} CVE" : "0";

        printf(
            "   %-28s | %-9s | %-9s | %-10s | %-12s\n",
            $short_name,
            $t['current_version'],
            $t['latest_version'],
            $status_label,
            $cve_label
        );

        if ($cve_count > 0) {
            foreach ($t['cves'] as $cve) {
                echo "       ↳ " . $cve['cve'] . " [" . $cve['severity'] . "] " . $cve['name'] . "\n";
            }
        }
    }
    echo $sep . "\n";
    exit;
}

// OUTPUT: HTML (Default per chiamate browser)
if (!$is_cli) {
    header('Content-Type: text/html; charset=UTF-8');
}
?>
<!DOCTYPE html><html lang="it">
<head>    <meta charset="UTF-8">
    <title>WordPress Security & Maintenance Panel</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif; background: #f0f2f5; margin: 0; padding: 25px; color: #1d2327; }
        .container { max-width: 1200px; margin: 0 auto; background: #fff; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.06); padding: 30px; }
        h1, h2 { color: #1d2327; margin-top: 0; }
        .meta-bar { background: #f8f9fa; border-left: 4px solid #2271b1; padding: 12px 18px; margin-bottom: 25px; font-size: 14px; }
        .alert-box { background: #e7f5ea; border-left: 4px solid #00a32a; padding: 15px; margin-bottom: 25px; border-radius: 4px; }
        .alert-box pre { margin: 5px 0 0; font-size: 13px; color: #333; }
        table { width: 100%; border-collapse: collapse; margin-bottom: 30px; font-size: 14px; }
        th, td { text-align: left; padding: 12px 14px; border-bottom: 1px solid #e2e8f0; vertical-align: top; }
        th { background: #f8fafc; font-weight: 600; color: #475569; }
        tr:hover { background: #fdfdfd; }
        .badge { display: inline-block; padding: 3px 8px; border-radius: 4px; font-size: 12px; font-weight: 600; }
        .badge-success { background: #dcfce7; color: #15803d; }
        .badge-warning { background: #fef9c3; color: #854d0e; }
        .badge-danger  { background: #fee2e2; color: #b91c1c; }
        .badge-muted   { background: #f1f5f9; color: #64748b; }
        .cve-list { margin: 6px 0 0; padding-left: 18px; font-size: 12px; color: #b91c1c; }
        .cve-list li { margin-bottom: 4px; }
        .cve-list a { color: #b91c1c; font-weight: bold; text-decoration: underline; }
    </style>
</head><body>
<div class="container">
    <h1>Pannello Manutenzione, Aggiornamenti & CVE WordPress</h1>
    <div class="meta-bar">
        <strong>Sito:</strong> <?= esc_html(get_bloginfo('name')) ?> (<?= esc_url(home_url()) ?>) &nbsp;|&nbsp;
        <strong>Data:</strong> <?= date('Y-m-d H:i:s') ?>
    </div>

    <?php if (!empty($update_results)): ?>
        <div class="alert-box">
            <strong>Risultati Operazione di Aggiornamento:</strong>
            <pre><?= esc_html(print_r($update_results, true)) ?></pre>
        </div>
    <?php endif; ?>

    <!-- SEZIONE CORE -->
    <h2>WordPress Core</h2>
    <table>
        <thead>            <tr>
                <th>Componente</th>
                <th>Versione Installata</th>
                <th>Ultima Release</th>
                <th>Stato</th>
                <th>Vulnerabilità CVE</th>
            </tr>
        </thead>        <tbody>
            <tr>
                <td><strong>WordPress Platform</strong></td>
                <td><?= esc_html($wp_version) ?></td>
                <td><?= esc_html($latest_core_version) ?></td>
                <td>
                    <?php if ($core_has_update): ?>
                        <span class="badge badge-warning">Aggiornabile (<?= esc_html($latest_core_version) ?>)</span>
                    <?php else: ?>
                        <span class="badge badge-success">Aggiornato</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if (!empty($core_cves)): ?>
                        <span class="badge badge-danger"><?= count($core_cves) ?> CVE Rilevati</span>
                        <ul class="cve-list">
                            <?php foreach ($core_cves as $c): ?>
                                <li>
                                    <a href="<?= esc_url($c['link']) ?>" target="_blank" rel="noopener"><?= esc_html($c['cve']) ?></a>
                                    (<?= esc_html($c['severity']) ?>): <?= esc_html($c['name']) ?>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php else: ?>
                        <span class="badge badge-success">Nessuna nota</span>
                    <?php endif; ?>
                </td>
            </tr>
        </tbody>
    </table>

    <!-- SEZIONE PLUGIN -->
    <h2>Plugin (<?= count($plugin_report) ?> installati)</h2>
    <table>
        <thead>            <tr>
                <th>Nome</th>
                <th>Slug</th>
                <th>Stato</th>
                <th>Installata</th>
                <th>Disponibile</th>
                <th>Aggiornamento</th>
                <th>CVE / Sicurezza</th>
            </tr>
        </thead>        <tbody>
            <?php foreach ($plugin_report as $p): ?>
                <tr>
                    <td><strong><?= esc_html($p['name']) ?></strong></td>
                    <td><code><?= esc_html($p['slug']) ?></code></td>
                    <td>
                        <span class="badge <?= $p['active'] ? 'badge-success' : 'badge-muted' ?>">
                            <?= $p['active'] ? 'Attivo' : 'Inattivo' ?>
                        </span>
                    </td>
                    <td><?= esc_html($p['current_version']) ?></td>
                    <td><?= esc_html($p['latest_version']) ?></td>
                    <td>
                        <?php if ($p['has_update']): ?>
                            <span class="badge badge-warning">Da Aggiornare</span>
                        <?php else: ?>
                            <span class="badge badge-success">Aggiornato</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if (!empty($p['cves'])): ?>
                            <span class="badge badge-danger"><?= count($p['cves']) ?> CVE</span>
                            <ul class="cve-list">
                                <?php foreach ($p['cves'] as $c): ?>
                                    <li>
                                        <a href="<?= esc_url($c['link']) ?>" target="_blank" rel="noopener"><?= esc_html($c['cve']) ?></a>
                                        (<?= esc_html($c['severity']) ?>): <?= esc_html($c['name']) ?>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else: ?>
                            <span class="badge badge-success">Sicuro</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!-- SEZIONE TEMI -->
    <h2>Temi / Template (<?= count($theme_report) ?> installati)</h2>
    <table>
        <thead>            <tr>
                <th>Nome Tema</th>
                <th>Cartella (Slug)</th>
                <th>Stato</th>
                <th>Installata</th>
                <th>Disponibile</th>
                <th>Aggiornamento</th>
                <th>CVE / Sicurezza</th>
            </tr>
        </thead>        <tbody>
            <?php foreach ($theme_report as $t): ?>
                <tr>
                    <td><strong><?= esc_html($t['name']) ?></strong></td>
                    <td><code><?= esc_html($t['slug']) ?></code></td>
                    <td>
                        <span class="badge <?= $t['active'] ? 'badge-success' : 'badge-muted' ?>">
                            <?= $t['active'] ? 'Attivo' : 'Inattivo' ?>
                        </span>
                    </td>
                    <td><?= esc_html($t['current_version']) ?></td>
                    <td><?= esc_html($t['latest_version']) ?></td>
                    <td>
                        <?php if ($t['has_update']): ?>
                            <span class="badge badge-warning">Da Aggiornare</span>
                        <?php else: ?>
                            <span class="badge badge-success">Aggiornato</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if (!empty($t['cves'])): ?>
                            <span class="badge badge-danger"><?= count($t['cves']) ?> CVE</span>
                            <ul class="cve-list">
                                <?php foreach ($t['cves'] as $c): ?>
                                    <li>
                                        <a href="<?= esc_url($c['link']) ?>" target="_blank" rel="noopener"><?= esc_html($c['cve']) ?></a>
                                        (<?= esc_html($c['severity']) ?>): <?= esc_html($c['name']) ?>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php else: ?>
                            <span class="badge badge-success">Sicuro</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
</body>
</html>

chiaramente MODIFICA_QUESTO_TOKEN_SICURO va modificato subito con una chiave che potete generare ad esempio con:

openssl rand -hex 16

Lo script si può poi richiamare con https://tuosito.com/wp-version-check.php?token=MODIFICA_QUESTO_TOKEN_SICURO

Infine, se si vuole avere la risposta in JSON si può passare il parametro?format=jsonovvero:
https://tuosito.com/wp-version-check.php?format=json&token=MODIFICA_QUESTO_TOKEN_SICURO

enjoy!

Ti interessa acquistare un dominio a prezzi ultraconvenienti? clicca qui

Se hai trovato utili le informazioni su questo blog,
Fai una donazione!
Clicca sul bottone qui sotto o almeno clicca sul banner pubblicitario 🙂



Commenta