• Resolved DJABHipHop

    (@pressthemes1)


    Feature Request: Server Insights Plugin for WordPress

    Overview: The Server Insights plugin is designed to enhance the WordPress dashboard by providing users with essential information about the server environment and performance metrics. It aims to present this information in a user-friendly interface, helping site administrators monitor and analyze server health efficiently.

    Key Features:

    1. Dashboard Integration:
      • Adds a dedicated widget to the WordPress dashboard displaying various server metrics.
    2. Tabbed Interface:
      • Organizes content into tabs for easy navigation between different metrics:
        • System Info: Displays detailed information about the server environment.
        • Memory Usage: Shows current and peak memory usage statistics.
        • Disk Space: Provides insights into disk usage across different directories (root, plugins, themes, uploads, etc.).
        • WordPress Speed: Displays metrics related to page load time and database queries.
    3. Comprehensive System Information:
      • Displays important server details including:
        • User and host information
        • Operating system details (name, type, version)
        • PHP and MySQL versions
        • SAPI (Server API) information
        • Cache status and uptime
    4. Memory Usage Statistics:
      • Provides insights into total RAM used and peak RAM usage.
      • For PHP 8.0 and above, it includes an option to reset RAM usage.
    5. Disk Space Utilization:
      • Measures and displays the sizes of various directories, such as:
        • Root directory
        • Plugin and theme directories
        • Uploads and cache directories
    6. WordPress Performance Metrics:
      • Calculates and shows metrics like:
        • Queries per second
        • Total page load time
        • Total database queries executed
        • Load average over the past minute, five minutes, and fifteen minutes
    7. User-Friendly Interface:
      • Utilizes the WordPress UI standards for a seamless experience.
      • Features responsive design and clear navigation with a clean layout.
    8. Customization and Extensibility:
      • Uses WordPress hooks for easy integration and compatibility with other plugins and themes.
      • Provides options for future expansion, such as additional metrics or settings.
    9. Security and Best Practices:
      • Implements necessary checks to prevent direct access and ensures data is sanitized before outputting to prevent XSS vulnerabilities.
    10. Styling and Presentation:
      • Includes custom styles to enhance the appearance of the dashboard widget, ensuring it blends well with the WordPress admin interface.
    <?php
    /*
    Plugin Name: Server Insights
    Plugin URI:
    Description: Monitor and display essential server information, including PHP memory usage, disk space, and server div, directly from your WordPress dashboard.
    Version: 1.0
    Author: DJABHipHop
    Author URI:
    License: GPLv2 or later
    Text Domain: server_insights
    */

    if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
    }

    class Server_Insights {
    public function __construct() {
    // Define constants
    if (!defined('CURRENT_PHP_VERSION')) {
    define('CURRENT_PHP_VERSION', explode('-', PHP_VERSION)[0]);
    }
    if (!defined('USEAGE')) {
    define('USEAGE', getrusage());
    }

    add_action('wp_dashboard_setup', [$this, 'setup_dashboard_widget']);
    add_action('admin_head', [$this, 'admin_styles']);
    }

    public function setup_dashboard_widget() {
    wp_add_dashboard_widget(
    'server_insights_dashboard_widget',
    '<span aria-hidden="true" class="dashicons dashicons-info"></span> <span class="screen-reader-text">Info: </span>' . esc_html__('Server Insights', 'server_insights'),
    [$this, 'dashboard_content']
    );
    }

    public function dashboard_content() {
    $active_tab = $this->get_active_tab();
    echo '<div id="activity-widget">';
    echo '<h1 class="nav-tab-wrapper si-tabs">';
    echo $this->render_tab('system_info', $active_tab);
    echo $this->render_tab('memory_usage', $active_tab);
    echo $this->render_tab('disk_space', $active_tab);
    echo $this->render_tab('wordpress_speed', $active_tab);
    echo '</h1>';
    echo '<div class="tabs-content">';

    // Display content based on active tab
    switch ($active_tab) {
    case 'memory_usage':
    $this->display_memory_usage();
    break;
    case 'disk_space':
    $this->display_disk_space();
    break;
    case 'wordpress_speed':
    $this->display_wordpress_speed();
    break;
    case 'system_info':
    default:
    $this->display_system_info();
    break;
    }

    echo '</div></div>';
    }

    private function render_tab($tab, $active_tab) {
    return '<a href="?tab=' . esc_attr($tab) . '" class="nav-tab ' . ($active_tab == $tab ? 'nav-tab-active si-tab-active' : '') . '">' . __(ucwords(str_replace('_', ' ', $tab)), 'server_insights') . '</a>';
    }

    private function display_system_info() {
    global $wpdb;

    // Get OS release name if available
    $lsb_release = f(ile_exists('/etc/lsb-release') ? parse_ini_file('/etc/lsb-release')['DISTRIB_DESCRIPTION'] ?? 'N/A' : 'N/A');

    // Mapping for user-friendly SAPI names
    $sapi_map = [
    'apache2handler' => 'Apache (mod_php)',
    'cli' => 'Command Line Interface (CLI)',
    'cgi-fcgi' => 'CGI/FastCGI',
    'apache' => 'Apache (CGI)',
    'fpm-fcgi' => 'PHP-FPM (FastCGI)',
    'litespeed' => 'LiteSpeed',
    'embed' => 'Embedded',
    ];

    // Get SAPI name and format it
    $sapi_name = php_sapi_name();
    $user_friendly_sapi = ($sapi_map[$sapi_name] ?? ucfirst($sapi_name);) // Use mapping or default

    // Gather system info
    $system_info = [
    'User' => get_current_user(),
    'Host Name' => gethostname(),
    'OS' => $lsb_release,
    'OS Type' => php_uname('s'),
    'OS Version' => (php_uname('v') ?: PHP_OS_FAMILY),
    'Machine Type' => php_uname('m'),
    'Kernel Name' => php_uname('r'),
    'Uptime' => $this->get_up_time(),
    'Cache Status' => f(unction_exists('wp_cache_get') ? esc_html__('Enabled', 'server_insights') : esc_html__('Disabled', 'server_insights')),
    'PHP Version' => CURRENT_PHP_VERSION,
    'Zend Version' => zend_version(),
    'GD Version' => gd_info()['GD Version'] ?? 'N/A',
    'Apache Version' => ($_SERVER['SERVER_SOFTWARE'] ? explode(' ', $_SERVER['SERVER_SOFTWARE'])[0] : 'N/A'),
    'MySQL Version' => $wpdb->db_version(),
    'SAPI Version' => $user_friendly_sapi,
    'User Time' => (USEAGE["ru_utime.tv_sec"] + USEAGE["ru_utime.tv_usec"] / 1e6),
    'System Time' => (USEAGE["ru_stime.tv_sec"] + USEAGE["ru_stime.tv_usec"] / 1e6),
    'Max Resident Set Size' => $this->bytes_to_size(USEAGE["ru_maxrss"]),
    ];

    $this->display_table($system_info);
    }

    private function display_memory_usage() {
    // Initialize the memory usage array
    $memory_usage = [
    'Total RAM Used' => memory_get_usage(),
    'Peak RAM Usage' => memory_get_peak_usage(),
    ];

    // Check if PHP version is 8.0 or higher
    if ($this->is_php_version_newer_or_equal('8.0.0')) {
    $memory_usage['Reset RAM Usage'] = memory_reset_peak_usage();
    }

    $this->display_table($memory_usage);
    }

    private function display_disk_space() {
    // Get the sizes of various directories
    $disk_space = [
    'Root directory size' => $this->bytes_to_size($this->get_dir_size(ABSPATH)),
    'Plugin directory size' => $this->bytes_to_size($this->get_dir_size(WP_PLUGIN_DIR)),
    'Themes directory size' => $this->bytes_to_size($this->get_dir_size(get_theme_root())),
    'Active Theme directory size' => $this->bytes_to_size($this->get_dir_size(get_stylesheet_directory())),
    'Uploads directory size' => $this->bytes_to_size($this->get_dir_size(wp_upload_dir()['basedir'])),
    'Cache directory size' => $this->bytes_to_size($this->get_dir_size(WP_CONTENT_DIR . '/cache')),
    'Temp directory size' => $this->bytes_to_size($this->get_dir_size(WP_CONTENT_DIR . '/temp')),
    'Upgrade directory size' => $this->bytes_to_size($this->get_dir_size(WP_CONTENT_DIR . '/upgrade')),
    'Languages directory size' => $this->bytes_to_size($this->get_dir_size(WP_CONTENT_DIR . '/languages')),
    ];

    $this->display_table($disk_space);
    }

    private function display_wordpress_speed() {
    // Prepare an array to hold the metrics
    $speed_metrics = [
    'Queries Per Second' => number_format(get_num_queries() / timer_stop(0), 2) . ' | ' . timer_stop(0) . ' seconds',
    'Total Page Load Time' => timer_stop(0) . ' seconds',
    'Total Database Queries' => get_num_queries(),
    'Load Average' => $this->get_load_average(),
    ];

    $this->display_table($speed_metrics);
    }

    private function get_load_average() {
    return implode(' | ', array_map('number_format', sys_getloadavg(), array_fill(0, 3, 2)));
    }

    private function bytes_to_size($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
    $factor = floor((strlen($bytes) - 1) / 3);
    return esc_html(round($bytes / pow(1024, $factor), $precision) . ' ' . $units[$factor]);
    }

    private function get_dir_size($directory) {
    if (!is_dir($directory)) {
    return (is_file($directory) ? filesize($directory) : 0); // Return file size or 0
    }

    $totalSize = 0;
    $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS));

    foreach ($iterator as $file) {
    if ($file->isFile()) {
    $totalSize += $file->getSize(); // Sum the sizes of files only
    }
    }

    return $totalSize;
    }

    private function get_up_time() {
    $str = @file_get_contents('/proc/uptime');
    if ($str === false) {
    return 'Unable to retrieve uptime';
    }

    $num = floatval($str);
    $days = floor($num / 86400);
    $hours = floor(($num % 86400) / 3600);
    $mins = floor(($num % 3600) / 60);
    return "{$days} days, " . str_pad($hours, 2, '0', STR_PAD_LEFT) . ':' . str_pad($mins, 2, '0', STR_PAD_LEFT);
    }

    private function is_php_version_newer_or_equal($version) {
    return version_compare(CURRENT_PHP_VERSION, $version, '>=');
    }

    public function get_active_tab() {
    $user_id = get_current_user_id();
    $active_tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : get_user_meta($user_id, 'server_insights_active_tab', true);
    if ($active_tab) {
    update_user_meta($user_id, 'server_insights_active_tab', $active_tab);
    }
    return $active_tab ?: 'system_info'; // Default tab
    }

    private function display_table($data) {
    echo '<table class="wp-list-table striped widefat form-table si-list-table"><tbody>';
    foreach ($data as $label => $value) {
    echo '<tr><td scope="row"><strong>' . esc_html($label) . ':</strong> ' . esc_html($value) . '</td></tr>';
    }
    echo '</tbody></table>';
    }

    public function admin_styles() {
    echo '<style>
    #server_insights_dashboard_widget .dashicons-info {
    color: #367ad6;
    padding-right: 3px;
    }
    #server_insights_dashboard_widget .si-tabs {
    margin-left: 0;
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none 0;
    }
    #server_insights_dashboard_widget .si-tabs .nav-tab:first-child {
    margin-left: 0;
    }
    #server_insights_dashboard_widget .si-tabs .nav-tab:last-child {
    margin-right: 0;
    }
    #server_insights_dashboard_widget .si-tabs .si-tab-active {
    color: #fff;
    background: #3c434a;
    border-color: #3c434a;
    }
    #server_insights_dashboard_widget h2 {
    display: inline-block;
    }
    #server_insights_dashboard_widget .si-list-table {
    margin-top: 0;
    padding-top: 0;
    }
    </style>';
    }
    }

    // Initialize the plugin
    new Server_Insights();
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • You must be logged in to reply to this topic.