Skip to content
McStay Designs

Wordpress tech Development

McStay Designs

Wordpress tech Development

  • Network benchmark
  • Get a Quote
  • Free code Projects
  • Free plugins
  • About
  • Network benchmark
  • Get a Quote
  • Free code Projects
  • Free plugins
  • About
McStay Designs

Wordpress tech Development

McStay Designs

Wordpress tech Development

  • Network benchmark
  • Get a Quote
  • Free code Projects
  • Free plugins
  • About
  • Network benchmark
  • Get a Quote
  • Free code Projects
  • Free plugins
  • About
Home/Free code Projects/WP Dashboard Heart Monitor (Auto-CPR Edition)
Free code Projects

WP Dashboard Heart Monitor (Auto-CPR Edition)

By mkmcst
September 3, 2026 14 Min Read
0
/**
 * Plugin Name: WP Dashboard Heart Monitor (Auto-CPR Edition)
 * Description: Real-time EKG oscilloscope with Auto-CPR automatic defibrillation, Blood Lab diagnostics, Treadmill stress testing, and WP-Cron task monitoring.
 * Version: 1.8.0
 * Author: WP Health Monitor
 */

if (!defined('ABSPATH')) {
    exit;
}

class WP_Dashboard_Heart_Monitor_Cron {

    public function __construct() {
        add_action('wp_dashboard_setup', array($this, 'add_dashboard_widget'));
        add_action('rest_api_init', array($this, 'register_rest_routes'));
    }

    public function add_dashboard_widget() {
        wp_add_dashboard_widget(
            'wp_heart_monitor_widget',
            'WP System Heart Monitor [Auto-CPR Edition]',
            array($this, 'render_widget')
        );
    }

    public function register_rest_routes() {
        register_rest_route('wp-heart-monitor/v1', '/status', array(
            'methods'  => 'GET',
            'callback' => array($this, 'get_site_telemetry'),
            'permission_callback' => function() { return current_user_can('edit_posts'); }
        ));

        register_rest_route('wp-heart-monitor/v1', '/defibrillate', array(
            'methods'  => 'POST',
            'callback' => array($this, 'execute_defibrillator'),
            'permission_callback' => function() { return current_user_can('manage_options'); }
        ));

        register_rest_route('wp-heart-monitor/v1', '/treadmill', array(
            'methods'  => 'POST',
            'callback' => array($this, 'run_treadmill_test'),
            'permission_callback' => function() { return current_user_can('manage_options'); }
        ));

        register_rest_route('wp-heart-monitor/v1', '/cron', array(
            'methods'  => 'GET',
            'callback' => array($this, 'get_cron_telemetry'),
            'permission_callback' => function() { return current_user_can('edit_posts'); }
        ));

        register_rest_route('wp-heart-monitor/v1', '/cron/spawn', array(
            'methods'  => 'POST',
            'callback' => array($this, 'force_spawn_cron'),
            'permission_callback' => function() { return current_user_can('manage_options'); }
        ));
    }

    /**
     * Inspect WP-Cron Queue & Identify Overdue / Heavy Tasks
     */
    public function get_cron_telemetry() {
        $crons = _get_cron_array();
        if (empty($crons) || !is_array($crons)) {
            return rest_ensure_response(array(
                'total_crons' => 0,
                'stuck_count' => 0,
                'cron_tasks'  => array()
            ));
        }

        $now = time();
        $cron_tasks = array();
        $stuck_count = 0;

        foreach ($crons as $timestamp => $hooks) {
            $is_overdue = ($timestamp < $now);
            $diff = abs($now - $timestamp);

            foreach ($hooks as $hook => $data) {
                foreach ($data as $key => $event) {
                    $schedule = isset($event['schedule']) && $event['schedule'] ? $event['schedule'] : 'Non-repeating';
                    
                    // Mark as stuck if overdue by more than 5 minutes (300s)
                    $is_stuck = ($is_overdue && $diff > 300);
                    if ($is_stuck) {
                        $stuck_count++;
                    }

                    $cron_tasks[] = array(
                        'hook'       => $hook,
                        'timestamp'  => $timestamp,
                        'schedule'   => $schedule,
                        'is_overdue' => $is_overdue,
                        'is_stuck'   => $is_stuck,
                        'time_label' => $is_overdue 
                            ? sprintf('%s ago', human_time_diff($timestamp, $now)) 
                            : sprintf('in %s', human_time_diff($now, $timestamp))
                    );
                }
            }
        }

        // Sort: Stuck & Overdue crons first
        usort($cron_tasks, function($a, $b) {
            if ($a['is_stuck'] !== $b['is_stuck']) {
                return $b['is_stuck'] ? 1 : -1;
            }
            return $a['timestamp'] <=> $b['timestamp'];
        });

        return rest_ensure_response(array(
            'total_crons' => count($cron_tasks),
            'stuck_count' => $stuck_count,
            'cron_tasks'  => array_slice($cron_tasks, 0, 15)
        ));
    }

    /**
     * Force Spawn WP-Cron Runner via Non-blocking HTTP POST
     */
    public function force_spawn_cron() {
        spawn_cron();
        return rest_ensure_response(array(
            'success' => true,
            'message' => 'WP-Cron process spawned successfully!'
        ));
    }

    public function run_treadmill_test() {
        global $wpdb;
        $start_time = microtime(true);

        $hash_count = 50000;
        $dummy_string = "wp_stress_test_" . rand(1000, 9999);
        for ($i = 0; $i < $hash_count; $i++) {
            hash('sha256', $dummy_string . $i);
        }
        $cpu_duration = microtime(true) - $start_time;

        $db_start_time = microtime(true);
        $wpdb->get_results("SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = 'post' ORDER BY RAND() LIMIT 25");
        $wpdb->get_results("SELECT option_name FROM {$wpdb->options} ORDER BY LENGTH(option_value) DESC LIMIT 25");
        $db_duration = microtime(true) - $db_start_time;
        
        $total_duration = microtime(true) - $start_time;
        $score = round(1000 / max(0.001, $total_duration));

        return rest_ensure_response(array(
            'success'      => true,
            'score'        => $score,
            'total_time_s' => round($total_duration, 4),
            'cpu_time_s'   => round($cpu_duration, 4),
            'db_time_ms'   => round($db_duration * 1000, 2)
        ));
    }

    public function execute_defibrillator() {
        global $wpdb;
        $opcache_cleared = false;
        if (function_exists('opcache_reset')) { $opcache_cleared = @opcache_reset(); }
        $object_cache_cleared = wp_cache_flush();
        $deleted_transients = $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_%' OR option_name LIKE '_site_transient_%'");
        do_action('wp_heart_monitor_defibrillate');

        return rest_ensure_response(array(
            'success' => true,
            'timestamp' => current_time('mysql')
        ));
    }

    public function get_site_telemetry() {
        global $wpdb;

        $start_time = microtime(true);
        $wpdb->get_var("SELECT 1");
        $db_latency = round((microtime(true) - $start_time) * 1000, 2);

        $memory_used = memory_get_usage(true);
        $limit_bytes = wp_convert_hr_to_bytes(ini_get('memory_limit'));
        $memory_percent = ($limit_bytes > 0) ? round(($memory_used / $limit_bytes) * 100, 1) : 0;
        
        $autoload_bytes = (int) $wpdb->get_var("SELECT SUM(OCTET_LENGTH(option_value)) FROM {$wpdb->options} WHERE autoload IN ('yes', 'on', '1')");
        $autoload_size_kb = round($autoload_bytes / 1024, 1);

        $top_options_raw = $wpdb->get_results("SELECT option_name, OCTET_LENGTH(option_value) AS option_size FROM {$wpdb->options} WHERE autoload IN ('yes', 'on', '1') ORDER BY option_size DESC LIMIT 5");
        $top_options = array();
        foreach ($top_options_raw as $opt) {
            $top_options[] = array('name' => $opt->option_name, 'size_kb' => round($opt->option_size / 1024, 1));
        }

        if (!function_exists('get_plugins')) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; }
        $all_installed_plugins = get_plugins();
        $active_plugins_raw = (array) get_option('active_plugins', array());
        $active_plugins = array();

        foreach ($active_plugins_raw as $plugin_path) {
            if (isset($all_installed_plugins[$plugin_path]['Name'])) {
                $active_plugins[] = $all_installed_plugins[$plugin_path]['Name'];
            } else {
                $parts = explode('/', $plugin_path);
                $active_plugins[] = isset($parts[0]) ? ucwords(str_replace('-', ' ', $parts[0])) : $plugin_path;
            }
        }

        $status = 'HEALTHY';
        if ($db_latency > 150 || $memory_percent > 85 || $autoload_size_kb > 800) { $status = 'WARNING'; }
        if ($db_latency > 400 || $memory_percent > 95 || $autoload_size_kb > 1500) { $status = 'CRITICAL'; }

        return rest_ensure_response(array(
            'db_latency_ms'       => $db_latency,
            'memory_percent'      => $memory_percent,
            'status'               => $status,
            'autoload_size_kb'     => $autoload_size_kb,
            'top_autoload_options' => $top_options,
            'active_plugins'       => $active_plugins,
        ));
    }

    public function render_widget() {
        $rest_url      = esc_url_raw(rest_url('wp-heart-monitor/v1/status'));
        $defib_url     = esc_url_raw(rest_url('wp-heart-monitor/v1/defibrillate'));
        $treadmill_url = esc_url_raw(rest_url('wp-heart-monitor/v1/treadmill'));
        $cron_url      = esc_url_raw(rest_url('wp-heart-monitor/v1/cron'));
        $cron_spawn    = esc_url_raw(rest_url('wp-heart-monitor/v1/cron/spawn'));
        $nonce         = wp_create_nonce('wp_rest');
        ?>
        <div id="wp-ekg-container">
            <div class="ekg-screen" id="ekgScreen">
                <div class="ekg-grid-overlay"></div>
                <div id="defibFlash" class="defib-flash-overlay"></div>
                <div id="cprFlash" class="cpr-flash-overlay"></div>
                
                <div id="treadmillModal" class="treadmill-modal">
                    <h3 style="color:#ffcc00; margin:0 0 10px 0;">🏃‍♂️ STRESS TEST COMPLETE</h3>
                    <div class="tm-score" id="tmScore">----</div>
                    <div class="tm-details">
                        <span id="tmCpu">CPU: -- s</span> | <span id="tmDb">DB: -- ms</span>
                    </div>
                    <button type="button" class="ekg-btn" style="margin-top:15px;" onclick="document.getElementById('treadmillModal').style.display='none'">CLOSE</button>
                </div>

                <canvas id="ekgCanvas"></canvas>
                
                <div class="ekg-overlay-left">
                    <button id="ekgAudioBtn" type="button" class="ekg-btn muted"><span class="icon">🔇</span></button>
                    <button id="ekgAutoCprBtn" type="button" class="ekg-btn cpr-btn">🫀 AUTO-CPR: OFF</button>
                    <button id="ekgDefibBtn" type="button" class="ekg-btn defib-btn">⚡ DEFIBRILLATE</button>
                    <button id="ekgBloodLabBtn" type="button" class="ekg-btn blood-lab-btn">🩸 BLOOD LAB</button>
                    <button id="ekgTreadmillBtn" type="button" class="ekg-btn treadmill-btn">🏃‍♂️ TREADMILL</button>
                    <button id="ekgCronBtn" type="button" class="ekg-btn cron-btn">⏱️ CRON (<span id="cronBadgeCount">0</span>)</button>
                </div>

                <div class="ekg-overlay-right">
                    <span id="ekgBpm">-- <small>BPM</small></span>
                    <span id="ekgStatus">INITIALIZING</span>
                </div>
            </div>
            
            <div class="ekg-readouts">
                <div class="readout-box"><span class="label">DB Latency</span><span class="value" id="valDb">-- ms</span></div>
                <div class="readout-box"><span class="label">RAM Load</span><span class="value" id="valRam">--%</span></div>
                <div class="readout-box"><span class="label">Autoload Bloat</span><span class="value" id="valAutoload">-- KB</span></div>
            </div>

            <div id="defibNotify" class="defib-notify-bar">SYSTEM STABLE</div>

            <!-- BLOOD LAB TRAY -->
            <div id="bloodLabTray" class="blood-lab-tray collapsed">
                <div class="blood-lab-header">
                    <h4>🩸 BLOOD LAB DIAGNOSTIC PANEL</h4>
                    <span id="autoloadBadge" class="lab-badge badge-green">AUTOLOAD OK</span>
                </div>
                <div class="blood-lab-grid">
                    <div class="lab-card">
                        <div class="card-title">Autoload Heavy Hogs</div>
                        <ul id="topAutoloadList" class="lab-list"><li>Loading...</li></ul>
                    </div>
                    <div class="lab-card">
                        <div class="card-title">Active Plugins (<span id="pluginCount">0</span>)</div>
                        <div id="pluginTags" class="plugin-tags"><span class="plugin-tag">Loading...</span></div>
                    </div>
                </div>
            </div>

            <!-- CRON CARDIOLOGY TRAY -->
            <div id="cronTray" class="cron-tray collapsed">
                <div class="cron-header">
                    <h4>⏱️ CRON CARDIOLOGY (SCHEDULED TASKS)</h4>
                    <button id="spawnCronBtn" type="button" class="ekg-btn defib-btn" style="font-size:11px; padding:4px 8px;">⚡ FORCE SPAWN CRON</button>
                </div>
                <div class="cron-summary">
                    <span>Total Tasks: <strong id="cronTotalCount">0</strong></span> | 
                    <span>Stuck/Overdue: <strong id="cronStuckCount" style="color:#ff3333;">0</strong></span>
                </div>
                <ul id="cronTaskList" class="cron-task-list">
                    <li>Loading WP-Cron queue...</li>
                </ul>
            </div>
        </div>

        <style>
            #wp-ekg-container { background: #030804; border-radius: 10px; padding: 18px; font-family: 'Courier New', Courier, monospace; color: #00ff66; box-shadow: inset 0 0 20px rgba(0, 255, 102, 0.15); }
            .ekg-screen { position: relative; background: #010a03; border: 2px solid #006628; border-radius: 8px; overflow: hidden; height: 180px; box-shadow: 0 0 14px rgba(0, 255, 102, 0.2); }
            .ekg-grid-overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; pointer-events: none; background-image: linear-gradient(rgba(0, 255, 102, 0.1) 1px, transparent 1px), linear-gradient(90deg, rgba(0, 255, 102, 0.1) 1px, transparent 1px), linear-gradient(rgba(0, 255, 102, 0.04) 1px, transparent 1px), linear-gradient(90deg, rgba(0, 255, 102, 0.04) 1px, transparent 1px); background-size: 50px 50px, 50px 50px, 10px 10px, 10px 10px; z-index: 1; }
            .defib-flash-overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: #ffffff; opacity: 0; pointer-events: none; z-index: 10; transition: opacity 0.4s ease-out; }
            .cpr-flash-overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: #ff0055; opacity: 0; pointer-events: none; z-index: 11; transition: opacity 0.2s ease-out; }
            
            .treadmill-modal { display: none; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: rgba(0, 15, 5, 0.95); border: 2px solid #ffcc00; border-radius: 8px; padding: 20px; z-index: 20; text-align: center; box-shadow: 0 0 30px rgba(255, 204, 0, 0.4); width: 80%; }
            .tm-score { font-size: 48px; font-weight: 900; color: #ffcc00; text-shadow: 0 0 15px #ffcc00; margin: 10px 0; }
            .tm-details { font-size: 14px; color: #fff; font-weight: bold; }
            
            #ekgCanvas { width: 100%; height: 180px; display: block; position: relative; z-index: 2; }
            .ekg-overlay-left { position: absolute; top: 12px; left: 12px; z-index: 4; display: flex; gap: 8px; flex-wrap: wrap; }
            .ekg-overlay-right { position: absolute; top: 12px; right: 16px; text-align: right; z-index: 3; }
            
            .ekg-btn { background: rgba(0, 25, 12, 0.9); border: 2px solid #00ff66; color: #00ff66; padding: 6px 12px; font-family: inherit; font-size: 13px; font-weight: bold; border-radius: 5px; cursor: pointer; transition: all 0.2s ease; text-shadow: 0 0 6px #00ff66; }
            .ekg-btn:hover { background: rgba(0, 255, 102, 0.25); }
            .ekg-btn.muted { border-color: #666; color: #aaa; text-shadow: none; }
            
            .cpr-btn { border-color: #ff9900; color: #ff9900; text-shadow: 0 0 6px #ff9900; background: rgba(50, 25, 0, 0.85); }
            .cpr-btn:hover, .cpr-btn.active { background: rgba(255, 153, 0, 0.35); box-shadow: 0 0 12px rgba(255, 153, 0, 0.7); }
            .cpr-btn.active { border-color: #ff3300; color: #ffddaa; animation: pulseCpr 1s infinite alternate; }

            .defib-btn { border-color: #ff3333; color: #ff3333; text-shadow: 0 0 6px #ff3333; background: rgba(50, 0, 0, 0.85); }
            .defib-btn:hover { background: rgba(255, 51, 51, 0.35); box-shadow: 0 0 12px rgba(255, 51, 51, 0.7); }
            .defib-btn.charging { animation: pulseWarning 0.5s infinite alternate; }
            
            .blood-lab-btn { border-color: #ff3366; color: #ff3366; text-shadow: 0 0 6px #ff3366; background: rgba(50, 0, 20, 0.85); }
            .blood-lab-btn:hover, .blood-lab-btn.active { background: rgba(255, 51, 102, 0.35); box-shadow: 0 0 12px rgba(255, 51, 102, 0.6); }

            .treadmill-btn { border-color: #ffcc00; color: #ffcc00; text-shadow: 0 0 6px #ffcc00; background: rgba(50, 40, 0, 0.85); }
            .treadmill-btn:hover { background: rgba(255, 204, 0, 0.35); box-shadow: 0 0 12px rgba(255, 204, 0, 0.6); }
            .treadmill-btn.running { animation: pulseTreadmill 0.3s infinite alternate; }

            .cron-btn { border-color: #00ccff; color: #00ccff; text-shadow: 0 0 6px #00ccff; background: rgba(0, 40, 50, 0.85); }
            .cron-btn:hover, .cron-btn.active { background: rgba(0, 204, 255, 0.35); box-shadow: 0 0 12px rgba(0, 204, 255, 0.6); }

            @keyframes pulseWarning { 0% { background: rgba(255, 51, 51, 0.2); } 100% { background: rgba(255, 51, 51, 0.9); color: #fff; } }
            @keyframes pulseCpr { 0% { background: rgba(255, 153, 0, 0.2); } 100% { background: rgba(255, 51, 0, 0.9); color: #fff; } }
            @keyframes pulseTreadmill { 0% { background: rgba(255, 204, 0, 0.2); } 100% { background: rgba(255, 204, 0, 0.9); color: #000; } }
            
            #ekgBpm { font-size: 32px; font-weight: 900; display: block; color: #00ff66; text-shadow: 0 0 10px #00ff66; }
            #ekgStatus { font-size: 13px; font-weight: bold; padding: 4px 10px; background: rgba(0, 255, 102, 0.2); border: 1px solid rgba(0, 255, 102, 0.6); border-radius: 4px; color: #00ff66; display: inline-block; margin-top: 4px; }
            
            .ekg-readouts { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 12px; margin-top: 14px; }
            .readout-box { background: #08150c; padding: 12px 10px; border-radius: 6px; border: 1px solid #004d1e; text-align: center; }
            .readout-box .label { display: block; font-size: 12px; color: #00cc52; font-weight: bold; text-transform: uppercase; margin-bottom: 4px; }
            .readout-box .value { font-size: 20px; font-weight: bold; color: #88ffbb; text-shadow: 0 0 6px rgba(0, 255, 102, 0.3); }
            .defib-notify-bar { margin-top: 10px; font-size: 13px; font-weight: bold; text-align: center; color: #00ff66; letter-spacing: 1px; }

            .blood-lab-tray { margin-top: 14px; background: #08111a; border: 2px solid #ff3366; border-radius: 8px; padding: 16px; box-shadow: 0 0 20px rgba(255, 51, 102, 0.2); transition: all 0.3s ease-in-out; }
            .blood-lab-tray.collapsed { display: none; }
            .blood-lab-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(255, 51, 102, 0.4); padding-bottom: 10px; margin-bottom: 12px; }
            .blood-lab-header h4 { margin: 0; font-size: 14px; font-weight: bold; color: #ff3366; }
            .lab-badge { font-size: 12px; padding: 4px 8px; border-radius: 4px; font-weight: bold; }
            .badge-green { background: rgba(0, 255, 102, 0.25); color: #00ff66; border: 1px solid #00ff66; }
            .badge-yellow { background: rgba(255, 204, 0, 0.25); color: #ffcc00; border: 1px solid #ffcc00; }
            .badge-red { background: rgba(255, 51, 51, 0.25); color: #ff3333; border: 1px solid #ff3333; }

            .blood-lab-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
            .lab-card { background: rgba(0, 0, 0, 0.5); border: 1px solid rgba(255, 51, 102, 0.3); border-radius: 6px; padding: 12px; }
            .card-title { font-size: 13px; font-weight: bold; color: #ff99bb; margin-bottom: 8px; text-transform: uppercase; }
            .lab-list { list-style: none; margin: 0; padding: 0; font-size: 13px; }
            .lab-list li { display: flex; justify-content: space-between; padding: 5px 0; border-bottom: 1px dashed rgba(255, 255, 255, 0.1); }
            .lab-list .opt-name { color: #dddddd; max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
            .lab-list .opt-size { color: #ff3366; font-weight: bold; }

            .plugin-tags { display: flex; flex-wrap: wrap; gap: 6px; max-height: 140px; overflow-y: auto; padding-right: 4px; }
            .plugin-tag { font-size: 12px; font-weight: bold; background: rgba(0, 255, 102, 0.15); color: #66ffa3; border: 1px solid rgba(0, 255, 102, 0.4); padding: 4px 8px; border-radius: 4px; }

            .cron-tray { margin-top: 14px; background: #04121a; border: 2px solid #00ccff; border-radius: 8px; padding: 16px; box-shadow: 0 0 20px rgba(0, 204, 255, 0.2); }
            .cron-tray.collapsed { display: none; }
            .cron-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(0, 204, 255, 0.4); padding-bottom: 10px; margin-bottom: 10px; }
            .cron-header h4 { margin: 0; font-size: 14px; font-weight: bold; color: #00ccff; }
            .cron-summary { font-size: 12px; color: #88ddff; font-weight: bold; margin-bottom: 10px; }
            .cron-task-list { list-style: none; margin: 0; padding: 0; font-size: 13px; max-height: 200px; overflow-y: auto; }
            .cron-task-list li { display: flex; justify-content: space-between; align-items: center; padding: 6px 4px; border-bottom: 1px dashed rgba(0, 204, 255, 0.15); }
            .cron-hook { color: #ffffff; font-weight: bold; max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
            .cron-meta { font-size: 11px; color: #88bbdd; }
            .cron-tag-stuck { color: #ff3333; font-weight: bold; background: rgba(255, 51, 51, 0.2); padding: 2px 6px; border-radius: 4px; border: 1px solid #ff3333; }
            .cron-tag-ok { color: #00ff66; }
        </style>

        <script>
        (function() {
            const canvas = document.getElementById('ekgCanvas');
            const ctx = canvas.getContext('2d');
            const restUrl = '<?php echo $rest_url; ?>';
            const defibUrl = '<?php echo $defib_url; ?>';
            const treadmillUrl = '<?php echo $treadmill_url; ?>';
            const cronUrl = '<?php echo $cron_url; ?>';
            const cronSpawnUrl = '<?php echo $cron_spawn; ?>';
            const nonce = '<?php echo $nonce; ?>';

            function setupCanvas() {
                const dpr = window.devicePixelRatio || 1;
                const rect = canvas.getBoundingClientRect();
                canvas.width = rect.width * dpr;
                canvas.height = rect.height * dpr;
                ctx.scale(dpr, dpr);
                return { width: rect.width, height: rect.height };
            }

            let dims = setupCanvas();
            window.addEventListener('resize', () => { dims = setupCanvas(); });

            let x = 0;
            let dbLatency = 40;
            let status = 'HEALTHY';
            let points = new Array(Math.ceil(dims.width)).fill(dims.height / 2);
            let isTreadmillRunning = false;

            // Auto-CPR State tracking
            let autoCprEnabled = false;
            let criticalStrikeCount = 0;
            let lastCprTime = 0;
            const CPR_COOLDOWN_MS = 60000; // 60 sec minimum buffer between Auto-CPRs

            let audioCtx = null;
            let soundEnabled = false;

            function initAudio() {
                if (!audioCtx) { audioCtx = new (window.AudioContext || window.webkitAudioContext)(); }
                if (audioCtx.state === 'suspended') { audioCtx.resume(); }
            }

            function playBeep(freq = 880, duration = 0.08) {
                if (!soundEnabled || !audioCtx) return;
                try {
                    const osc = audioCtx.createOscillator();
                    const gain = audioCtx.createGain();
                    osc.type = 'sine';
                    osc.frequency.setValueAtTime(freq, audioCtx.currentTime);
                    gain.gain.setValueAtTime(0.12, audioCtx.currentTime);
                    gain.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + duration);
                    osc.connect(gain);
                    gain.connect(audioCtx.destination);
                    osc.start();
                    osc.stop(audioCtx.currentTime + duration);
                } catch(e) {}
            }

            const audioBtn = document.getElementById('ekgAudioBtn');
            const autoCprBtn = document.getElementById('ekgAutoCprBtn');
            const defibBtn = document.getElementById('ekgDefibBtn');
            const bloodLabBtn = document.getElementById('ekgBloodLabBtn');
            const treadmillBtn = document.getElementById('ekgTreadmillBtn');
            const cronBtn = document.getElementById('ekgCronBtn');
            const spawnCronBtn = document.getElementById('spawnCronBtn');

            const bloodLabTray = document.getElementById('bloodLabTray');
            const cronTray = document.getElementById('cronTray');
            const notifyBar = document.getElementById('defibNotify');

            audioBtn.addEventListener('click', function() {
                initAudio();
                soundEnabled = !soundEnabled;
                audioBtn.className = soundEnabled ? 'ekg-btn' : 'ekg-btn muted';
                audioBtn.innerHTML = soundEnabled ? '<span class="icon">🔊</span>' : '<span class="icon">🔇</span>';
                if (soundEnabled) playBeep(1000, 0.05);
            });

            autoCprBtn.addEventListener('click', function() {
                initAudio();
                autoCprEnabled = !autoCprEnabled;
                if (autoCprEnabled) {
                    autoCprBtn.classList.add('active');
                    autoCprBtn.innerText = '🫀 AUTO-CPR: ARMED';
                    notifyBar.innerText = 'AUTO-CPR ARMED: WILL AUTO-DEFIBRILLATE ON SUSTAINED CRITICAL';
                    playBeep(1100, 0.1);
                } else {
                    autoCprBtn.classList.remove('active');
                    autoCprBtn.innerText = '🫀 AUTO-CPR: OFF';
                    criticalStrikeCount = 0;
                    notifyBar.innerText = 'AUTO-CPR DISARMED';
                }
            });

            bloodLabBtn.addEventListener('click', function() {
                bloodLabTray.classList.toggle('collapsed');
                bloodLabBtn.classList.toggle('active');
            });

            cronBtn.addEventListener('click', function() {
                cronTray.classList.toggle('collapsed');
                cronBtn.classList.toggle('active');
                if (!cronTray.classList.contains('collapsed')) {
                    fetchCronTelemetry();
                }
            });

            spawnCronBtn.addEventListener('click', function() {
                initAudio();
                spawnCronBtn.disabled = true;
                notifyBar.innerText = 'SPAWNING WP-CRON...';
                
                fetch(cronSpawnUrl, {
                    method: 'POST',
                    headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json' }
                })
                .then(res => res.json())
                .then(data => {
                    notifyBar.innerText = '⚡ WP-CRON SPAWNED!';
                    spawnCronBtn.disabled = false;
                    fetchCronTelemetry();
                });
            });

            function fetchCronTelemetry() {
                fetch(cronUrl, { headers: { 'X-WP-Nonce': nonce } })
                .then(res => res.json())
                .then(data => {
                    document.getElementById('cronTotalCount').innerText = data.total_crons;
                    document.getElementById('cronStuckCount').innerText = data.stuck_count;
                    document.getElementById('cronBadgeCount').innerText = data.stuck_count > 0 ? data.stuck_count + ' STUCK' : data.total_crons;

                    const listEl = document.getElementById('cronTaskList');
                    listEl.innerHTML = '';

                    if (data.cron_tasks && data.cron_tasks.length) {
                        data.cron_tasks.forEach(task => {
                            const statusTag = task.is_stuck 
                                ? `<span class="cron-tag-stuck">STUCK (${task.time_label})</span>` 
                                : `<span class="cron-tag-ok">${task.time_label}</span>`;

                            listEl.innerHTML += `
                                <li>
                                    <div>
                                        <div class="cron-hook" title="${task.hook}">${task.hook}</div>
                                        <div class="cron-meta">Schedule: ${task.schedule}</div>
                                    </div>
                                    <div>${statusTag}</div>
                                </li>
                            `;
                        });
                    } else {
                        listEl.innerHTML = '<li>No scheduled tasks found.</li>';
                    }
                });
            }

            // Execute Defibrillate Action
            function triggerDefibrillator(isAutomatic = false) {
                initAudio();
                defibBtn.classList.add('charging');
                defibBtn.disabled = true;

                if (isAutomatic) {
                    notifyBar.innerText = '🫀 AUTO-CPR ENGAGED! DISCHARGING DEFIBRILLATOR...';
                    document.getElementById('cprFlash').style.opacity = '0.8';
                    setTimeout(() => { document.getElementById('cprFlash').style.opacity = '0'; }, 500);
                    playBeep(1600, 0.3);
                } else {
                    notifyBar.innerText = 'CHARGING DEFIBRILLATOR...';
                }

                setTimeout(() => {
                    document.getElementById('defibFlash').style.opacity = '0.9';
                    setTimeout(() => { document.getElementById('defibFlash').style.opacity = '0'; }, 300);

                    fetch(defibUrl, {
                        method: 'POST',
                        headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json' }
                    })
                    .then(res => res.json())
                    .then(data => {
                        notifyBar.innerText = isAutomatic 
                            ? '🫀 AUTO-CPR COMPLETE: CACHES PURGED & SYSTEM RESUSCITATED!' 
                            : '⚡ DISCHARGE COMPLETE: CACHES PURGED!';
                        defibBtn.classList.remove('charging');
                        defibBtn.disabled = false;
                        criticalStrikeCount = 0;
                        lastCprTime = Date.now();
                        fetchTelemetry();
                    });
                }, 400);
            }

            // TREADMILL LOGIC
            treadmillBtn.addEventListener('click', function() {
                initAudio();
                isTreadmillRunning = true;
                treadmillBtn.classList.add('running');
                treadmillBtn.disabled = true;
                notifyBar.innerText = 'STRESS TESTING SERVER (CPU & DB)...';

                fetch(treadmillUrl, {
                    method: 'POST',
                    headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json' }
                })
                .then(res => res.json())
                .then(data => {
                    isTreadmillRunning = false;
                    treadmillBtn.classList.remove('running');
                    treadmillBtn.disabled = false;
                    notifyBar.innerText = 'TEST COMPLETE';
                    
                    document.getElementById('tmScore').innerText = data.score;
                    document.getElementById('tmCpu').innerText = 'CPU: ' + data.cpu_time_s + 's';
                    document.getElementById('tmDb').innerText = 'DB: ' + data.db_time_ms + 'ms';
                    document.getElementById('treadmillModal').style.display = 'block';
                    
                    playBeep(1200, 0.2);
                    fetchTelemetry();
                });
            });

            // DEFIBRILLATOR BUTTON LOGIC
            defibBtn.addEventListener('click', function() {
                triggerDefibrillator(false);
            });

            function fetchTelemetry() {
                if (isTreadmillRunning) return;
                
                fetch(restUrl, { headers: { 'X-WP-Nonce': nonce } })
                .then(res => res.json())
                .then(data => {
                    dbLatency = data.db_latency_ms;
                    status = data.status;

                    document.getElementById('valDb').innerText = data.db_latency_ms + ' ms';
                    document.getElementById('valRam').innerText = data.memory_percent + '%';
                    document.getElementById('valAutoload').innerText = data.autoload_size_kb + ' KB';
                    
                    const calculatedBpm = Math.max(40, Math.min(180, Math.round(1000 / (dbLatency + 10) * 3)));
                    document.getElementById('ekgBpm').innerHTML = calculatedBpm + ' <small>BPM</small>';
                    
                    const statusEl = document.getElementById('ekgStatus');
                    statusEl.innerText = data.status;

                    if(data.status === 'CRITICAL') {
                        statusEl.style.color = '#ff3333'; statusEl.style.borderColor = '#ff3333'; statusEl.style.background = 'rgba(255,51,51,0.2)';
                        
                        // AUTO-CPR TRIGGER MONITORING
                        criticalStrikeCount++;
                        const now = Date.now();
                        const cprCooldownRemaining = Math.max(0, Math.ceil((CPR_COOLDOWN_MS - (now - lastCprTime)) / 1000));

                        if (autoCprEnabled) {
                            if (cprCooldownRemaining > 0) {
                                notifyBar.innerText = `⚠️ CRITICAL STATUS DETECTED! Auto-CPR Cooldown: ${cprCooldownRemaining}s`;
                            } else {
                                notifyBar.innerText = `⚠️ CRITICAL STRIKE ${criticalStrikeCount}/3 DETECTED!`;
                                if (criticalStrikeCount >= 3) {
                                    triggerDefibrillator(true);
                                }
                            }
                        }
                    } else if(data.status === 'WARNING') {
                        statusEl.style.color = '#ffcc00'; statusEl.style.borderColor = '#ffcc00'; statusEl.style.background = 'rgba(255,204,0,0.2)';
                        criticalStrikeCount = 0;
                    } else {
                        statusEl.style.color = '#00ff66'; statusEl.style.borderColor = 'rgba(0, 255, 102, 0.4)'; statusEl.style.background = 'rgba(0, 255, 102, 0.15)';
                        criticalStrikeCount = 0;
                    }

                    const topListEl = document.getElementById('topAutoloadList');
                    topListEl.innerHTML = '';
                    if (data.top_autoload_options) {
                        data.top_autoload_options.forEach(opt => {
                            topListEl.innerHTML += `<li><span class="opt-name" title="${opt.name}">${opt.name}</span><span class="opt-size">${opt.size_kb} KB</span></li>`;
                        });
                    }

                    document.getElementById('pluginCount').innerText = data.active_plugins ? data.active_plugins.length : 0;
                    const pluginTagsEl = document.getElementById('pluginTags');
                    pluginTagsEl.innerHTML = '';
                    if (data.active_plugins) {
                        data.active_plugins.forEach(plugName => {
                            pluginTagsEl.innerHTML += `<span class="plugin-tag">${plugName}</span>`;
                        });
                    }
                });
            }

            fetchTelemetry();
            fetchCronTelemetry();
            setInterval(fetchTelemetry, 3000);

            function draw() {
                const drawStatus = isTreadmillRunning ? 'WARNING' : status;
                const cycleSpeed = isTreadmillRunning ? 15 : 60; 
                
                let primary = '#00ff66', glow = '#00ff55', fade = 'rgba(1, 10, 3, 0.18)';
                if (drawStatus === 'CRITICAL') { primary = '#ff3333'; glow = '#ff0000'; fade = 'rgba(10, 1, 1, 0.18)'; }
                if (drawStatus === 'WARNING') { primary = '#ffcc00'; glow = '#ffaa00'; fade = 'rgba(10, 8, 1, 0.18)'; }
                
                ctx.fillStyle = fade;
                ctx.fillRect(0, 0, dims.width, dims.height);

                const midY = dims.height / 2;
                let y = midY;
                let step = x % cycleSpeed;

                if (isTreadmillRunning) {
                    if (step === 2) y = midY - 20;
                    else if (step === 4) y = midY + 40;
                    else if (step === 6) y = midY - 60;
                    else if (step === 8) { y = midY + 20; if (x % 30 === 8) playBeep(1400, 0.03); }
                    else y = midY + (Math.random() * 6 - 3);
                } else {
                    if (step === 10) y = midY - 8;
                    else if (step === 15) y = midY;
                    else if (step === 20) y = midY + 22;
                    else if (step === 23) {
                        y = midY - 65;
                        if (drawStatus === 'CRITICAL') playBeep(1200, 0.12);
                        else if (drawStatus === 'WARNING') playBeep(980, 0.09);
                        else playBeep(880, 0.07);
                    }
                    else if (step === 26) y = midY + 40;
                    else if (step === 30) y = midY;
                    else if (step === 40) y = midY - 14;
                    else y = midY + (Math.random() * 2 - 1);
                }

                points[x] = y;

                ctx.lineWidth = 4; ctx.strokeStyle = primary; ctx.shadowBlur = 12; ctx.shadowColor = glow;
                ctx.beginPath(); ctx.moveTo(0, points[0] || midY);
                for (let i = 1; i < dims.width; i++) { if (points[i] !== undefined) ctx.lineTo(i, points[i]); }
                ctx.stroke();

                ctx.lineWidth = 2.5; ctx.strokeStyle = '#ffffff'; ctx.shadowBlur = 4; ctx.shadowColor = primary;
                ctx.beginPath(); ctx.moveTo(0, points[0] || midY);
                for (let i = 1; i < dims.width; i++) { if (points[i] !== undefined) ctx.lineTo(i, points[i]); }
                ctx.stroke();

                ctx.fillStyle = '#ffffff'; ctx.shadowBlur = 15; ctx.shadowColor = glow;
                ctx.beginPath(); ctx.arc(x, y, 4, 0, Math.PI * 2); ctx.fill();

                x = (x + (isTreadmillRunning ? 3 : 1)) % Math.floor(dims.width);
                requestAnimationFrame(draw);
            }
            draw();
        })();
        </script>
        <?php
    }
}

new WP_Dashboard_Heart_Monitor_Cron();
Author

mkmcst

test test test

Follow Me
Other Articles
Previous

Visual Network Trace

Next

Monthly & Daily Posts Dashboard Widget Pro

No Comment! Be the first one.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Legal

  • Terms of Service
  • Privacy Policy
Copyright 2026 — McStay Designs. All rights reserved.McStay Media
🚀 Upgrade Your Site: 20% Off Custom WordPress Plugins, Security Cleanup & Performance Tuning!Get a Free Quote →