# plugin-memory-usage/1.1.0/plugin-memory-usage.php

Plugin Memory Usage, version 1.1.0. 729 lines.

- Page: https://pluginprobe.com/plugins/plugin-memory-usage/1.1.0/code/plugin-memory-usage.php
- Raw: https://pluginprobe.com/plugins/plugin-memory-usage/1.1.0/raw/plugin-memory-usage.php
- Modified: 2025-01-16T19:43:20+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/plugin-memory-usage/1.1.0/code/plugin-memory-usage.php#L10-L20`.

```php
<?php
/*
Plugin Name: Plugin Memory Usage
Plugin URI: https://nett.pro/en/plugins/
Description: Display different plugins memory usage and impact on Wordpress.
Version: 1.1.0
Author: NETT.PRO
Author URI: https://nett.pro/en/
License: GPLv3
*/

// Prevent direct access to this file
if (!defined('ABSPATH')) {
    exit;
}




function wpmem_wp_memory_usage_admin_menu() {
    add_menu_page(
        'Plugin Memory Usage',
        'Memory Usage',
        'manage_options',
        'wp_plugin_memory_usage',
        'wpmem_wp_memory_usage_admin_page',
        'dashicons-performance',
        100
    );
}
add_action('admin_menu', 'wpmem_wp_memory_usage_admin_menu');




// Function to register the dashboard widget
function wpmem_wp_memory_usage_widget() {
    wp_add_dashboard_widget(
        'wp_memory_usage',
        'Plugin Memory Usage',
        'wpmem_display_memory_usage_dashboard'
    );
}

// Function to display content in the dashboard widget
function wpmem_display_memory_usage_dashboard() {
    // Get PHP version
    $php_version = phpversion();
    
    // Get WordPress memory limit
    $wp_memory_limit = wp_convert_hr_to_bytes(WP_MEMORY_LIMIT);
    
    // Get PHP memory limit
    $php_memory_limit = ini_get('memory_limit');

    // Get current memory usage
    $current_memory_usage = memory_get_usage(true);

    // Calculate percentage used
    $percentage_used = ($current_memory_usage / $wp_memory_limit) * 100;

    // Display the data
    echo '<p><strong>PHP Version:</strong> ' . esc_html($php_version) . '</p>';
    echo '<p><strong>WordPress Memory Limit:</strong> ' . esc_html(size_format($wp_memory_limit)) . '</p>';
    echo '<p><strong>PHP Memory Limit:</strong> ' . esc_html($php_memory_limit) . '</p>';

    // Display memory usage
    echo '<h4>Current Memory Usage:</h4>';
    echo '<p>' . esc_html(size_format($current_memory_usage)) . ' of ' . esc_html(size_format($wp_memory_limit)) . '</p>';
    echo '<div style="width: 100%; background: #e0e0e0; height: 24px; border-radius: 10px; overflow: hidden;">
            <div style="width: ' . esc_html(round($percentage_used, 1)) . '%; background: #76c7c0; height: 100%; text-align: center; line-height: 24px;" class="memory-bar-fill">' . esc_html(round($percentage_used, 1)) . '%</div>
        </div>';

    // Message to increase memory limit if usage is high
    if ($current_memory_usage > $wp_memory_limit * 0.8) {
        echo 'You are using more than 80% of allocated memory. Please go to Memory Control Panel to try to increase memory limit ';
        echo '<p id="memory-increase-result"></p>';
    }



    // Add button to Plugin Memory Control Panel
    echo '<p><a href="' . esc_html(admin_url('admin.php?page=wp_plugin_memory_usage')) . '" class="button">Plugin Memory Control Panel</a></p>';
}

// Hook to add the widget to the dashboard
add_action('wp_dashboard_setup', 'wpmem_wp_memory_usage_widget');








function wpmem_wp_memory_usage_admin_page() {
    ?>
    <div class="wrap">
        <h1>Plugin Memory Usage - Control Panel</h1>
        
        <div class="card-container">
            <div class="card-row">
                <div class="card card-system-info">
                    <h2>System Information</h2>
                    <table class="widefat">
                        <tr>
                            <th>PHP Version</th>
                            <td><?php echo esc_html(phpversion()); ?></td>
                        </tr>
                        <tr>
                            <th>WordPress Memory Limit</th>
                            <td><?php echo esc_html(WP_MEMORY_LIMIT); ?></td>
                        </tr>
                        <tr>
                            <th>PHP Memory Limit</th>
                            <td><?php echo esc_html(ini_get('memory_limit')); ?></td>
                        </tr>
                        <tr>
                            <th>WordPress Version</th>
                            <td><?php echo esc_html(get_bloginfo('version')); ?></td>
                        </tr>
                    </table>
                </div>

                <div class="card card-memory-usage">
                    <h2>Current Memory Usage</h2>
                    <?php
                    $wp_memory_limit = wp_convert_hr_to_bytes(WP_MEMORY_LIMIT);
                    $current_memory_usage = memory_get_usage(true);
                    $percentage_used = ($current_memory_usage / $wp_memory_limit) * 100;
                    ?>
                    <p>Using <span id="current-memory"><?php echo esc_html(size_format($current_memory_usage)); ?></span> of <?php echo esc_html(size_format($wp_memory_limit)); ?></p>
                    <div class="memory-bar">
                        <div id="memory-bar-fill" class="memory-bar-fill" style="width: <?php echo esc_html(round($percentage_used, 1)); ?>%;">
                            <span id="memory-percentage"><?php echo esc_html(round($percentage_used, 1)); ?>%</span>
                        </div>
                    </div>

                    <br><button id="refresh-memory" class="button">Refresh Memory Usage</button>
                    <br><br>Memory fluctuate. Please press button once after entering panel.

                    <?php
                    if ($current_memory_usage > $wp_memory_limit * 0.8) {
                        echo '<p style="color:red;">You are using more than 80% of allocated memory. Please click button below to try to increase memory limit.</p> ';
                        echo '<p><button id="increase-memory-limit" class="button">Increase Memory Limit</button></p>';
                        echo '<p id="memory-increase-result"></p>';
                    }  ?>
                </div>

                <div class="card card-memory-history">
                    <h2>Memory Usage History</h2>
					
					<ul id="memory-history-list">
					
					
					<hr>
					<p>This plugin measures changes in WordPress memory usage as you activate and deactivate plugins. Here's how it works:</p>
					<ol>
						<li>It records the current memory usage of WordPress.</li>
						<li>When you activate or deactivate a plugin, it measures the memory usage again.</li>
						<li>The difference between these measurements gives an estimate of the plugin's memory impact.</li>
						<li>This process is repeated each time you toggle a plugin.</li>
					</ol>
					<p>Note: These measurements are estimates and may vary. Factors like caching, other active plugins, and WordPress itself can influence memory usage. For the most accurate results, consider testing in a controlled environment.</p>
					<p>To begin, try activating or deactivating plugins using the buttons provided. The memory usage history will appear here.</p>|
					
					
					
					</ul>
                </div>
            </div>

            <div class="card card-plugins">
                <h2>Plugins</h2>
                <?php
                $all_plugins = get_plugins();
                $active_plugins = get_option('active_plugins');





                echo '<ul class="plugin-list">';
                foreach ($all_plugins as $plugin_path => $plugin_data) {
    $is_active = in_array($plugin_path, $active_plugins);
    $plugin_id = sanitize_title($plugin_data['Name']);
    $is_memory_usage_plugin = (strpos($plugin_path, 'plugin-memory-usage') !== false);
    $li_class = $is_active ? 'plugin-active' : 'plugin-inactive';
    if ($is_memory_usage_plugin) {
        $li_class .= ' memory-usage-plugin';
    }
    $avg_memory = wpmem_get_average_memory_usage($plugin_path);
    
    echo '<li class="' . esc_attr($li_class) . '">';
    echo '<div class="plugin-info">';
    echo '<span class="plugin-name">' . esc_html($plugin_data['Name']) . ' <span class="avg-memory" title="The average memory usage represents the typical amount of memory consumed by this plugin over time.">(' . esc_html($avg_memory) . ' MB)</span></span>';
    echo '<div class="plugin-memory-bar" title="Absolute value of last memory change"><div class="plugin-memory-fill"><span class="plugin-memory-text"></span></div></div>';
    echo '</div>';
    echo '<div class="plugin-actions">';
    if ($is_memory_usage_plugin) {
        echo '<button class="button" disabled>Active</button>';
    } else {
        echo '<button class="button toggle-plugin" data-plugin="' . esc_attr($plugin_path) . '" data-action="' . ($is_active ? 'deactivate' : 'activate') . '">';
        echo $is_active ? 'Deactivate' : 'Activate';
        echo '</button>';
    }
    echo '</div>';
    echo '</li>';
}

                echo '</ul>';





                ?>
            </div>
        </div>
    </div>

    
    <?php
}





function wpmem_toggle_plugin() {
    check_ajax_referer('wp_memory_usage_nonce', 'nonce');
    if (!current_user_can('activate_plugins')) {
        wp_send_json_error('Insufficient permissions');
    }


    $plugin = isset($_POST['plugin']) ? sanitize_text_field(wp_unslash($_POST['plugin'])) : '';
    $action = isset($_POST['toggle_action']) ? sanitize_text_field(wp_unslash($_POST['toggle_action'])) : '';

    if (empty($plugin) || empty($action)) {
        wp_send_json_error('Invalid plugin or action');
        return;
    }



    if ($action === 'activate') {
        $result = activate_plugin($plugin);
    } else {
        $result = deactivate_plugins($plugin);
    }

    if (is_wp_error($result)) {
        wp_send_json_error($result->get_error_message());
    } else {
        wp_send_json_success();
    }
}
add_action('wp_ajax_toggle_plugin', 'wpmem_toggle_plugin');






function wpmem_table_exists($table_name) {
    global $wpdb;
    $full_table_name = $wpdb->prefix . $table_name;
    
    // Create a unique cache key
    $cache_key = 'wpmem_table_exists_' . md5($full_table_name);

    // Try to get the result from cache
    $table_exists = wp_cache_get($cache_key);

    if (false === $table_exists) {
        // Cache miss, perform the database query
		// There isn't a reliable way to check if a table exists in WordPress without making a direct database call
        $result = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            $wpdb->prepare(
                "SHOW TABLES LIKE %s",
                $full_table_name
            )
        );
        
        $table_exists = ($result === $full_table_name);

        // Cache the result for future use (cache for 1 hour)
        wp_cache_set($cache_key, $table_exists, '', 3600);
    }

    return $table_exists;
}





function wpmem_refresh_memory_usage() {
    check_ajax_referer('wp_memory_usage_nonce', 'nonce');

    global $wpdb;
    $table_name = $wpdb->prefix . 'wpmem_plugin_history';

    // Check if the table exists
    if (!wpmem_table_exists('wpmem_plugin_history')) {
        wpmem_create_history_table();
    }


    $current_memory = memory_get_usage(true);
    $formatted_memory = size_format($current_memory, 2);
    $percentage = round(($current_memory / wp_convert_hr_to_bytes(WP_MEMORY_LIMIT)) * 100, 2);

    // Save the measurement if a plugin was toggled
    if (isset($_POST['plugin']) && isset($_POST['toggle_action'])) {
        $plugin = sanitize_text_field(wp_unslash($_POST['plugin']));
        $previous_memory = isset($_POST['previous_memory']) ? intval($_POST['previous_memory']) : 0;
        $memory_change = $current_memory - $previous_memory;
        wpmem_save_plugin_measurement($plugin, $memory_change);
    }

    wp_send_json_success(array(
        'current_memory' => $formatted_memory,
        'current_memory_bytes' => $current_memory,
        'percentage' => $percentage,
    ));
}
add_action('wp_ajax_refresh_memory_usage', 'wpmem_refresh_memory_usage');




function wp_memory_usage_enqueue_styles($hook) {
    // Only load on our plugin's admin page
    if ($hook != 'toplevel_page_wp_plugin_memory_usage') {
        return;
    }
    wp_enqueue_style('wp-memory-usage-styles', plugins_url('plugin-memory-usage.css', __FILE__));
}
add_action('admin_enqueue_scripts', 'wp_memory_usage_enqueue_styles');





function wpmem_enqueue_scripts($hook) {
    if ($hook != 'toplevel_page_wp_plugin_memory_usage') {
        return;
    }
    wp_enqueue_script('wpmem-script', plugins_url('plugin-memory-usage.js', __FILE__), array(), '1.0', true);
    $nonce = wp_create_nonce('wp_memory_usage_nonce');
    wp_localize_script('wpmem-script', 'wpmemData', array(
        'wpmem_ajaxurl' => admin_url('admin-ajax.php'),
        'nonce' => $nonce,
        'initialMemoryUsage' => memory_get_usage(true),
        'pluginHistory' => wpmem_get_all_plugin_history()
    ));
}
add_action('admin_enqueue_scripts', 'wpmem_enqueue_scripts');





function wpmem_create_history_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wpmem_plugin_history';
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        plugin_path varchar(255) NOT NULL,
        memory_change bigint(20) NOT NULL,
        zero_count int(11) NOT NULL DEFAULT 0,
        timestamp datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
        PRIMARY KEY  (id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    $result = dbDelta($sql);
    
    if (!empty($wpdb->last_error)) {
        return false;
    }
    return true;
}


register_activation_hook(__FILE__, 'wpmem_create_history_table');



function wpmem_save_plugin_measurement($plugin_path, $memory_change) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wpmem_plugin_history';

	// Convert memory_change to its absolute value
    $memory_change = abs($memory_change);

    if ($memory_change == 0) {
        // Increment zero count for the most recent entry
        $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            $wpdb->prepare(
                "UPDATE `" . esc_sql($table_name) . "` SET zero_count = zero_count + 1 
                WHERE plugin_path = %s 
                ORDER BY timestamp DESC 
                LIMIT 1",
                $plugin_path
            )
        );
    } else {
        // Insert new non-zero measurement
        $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            $table_name,
            array(
                'plugin_path' => $plugin_path,
                'memory_change' => $memory_change,
                'zero_count' => 0,
            )
        );
    }

    // Clear caches
    wpmem_clear_plugin_history_cache($plugin_path);
    wpmem_clear_all_plugin_history_cache();
    wpmem_clear_average_memory_cache($plugin_path);
}



function wpmem_get_plugin_history($plugin_path) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wpmem_plugin_history';

    // Create a unique cache key for this query
    $cache_key = 'wpmem_plugin_history_' . md5($plugin_path);

    // Try to get the results from cache
    $results = wp_cache_get($cache_key);

    // If the results are not in cache, query the database
    if (false === $results) {
        $results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            $wpdb->prepare(
                "SELECT memory_change, timestamp FROM `" . esc_sql($table_name) . "` WHERE plugin_path = %s ORDER BY timestamp DESC LIMIT 5",
                $plugin_path
            )
        );

        // Cache the results for future use
        wp_cache_set($cache_key, $results, '', 3600); // Cache for 1 hour
    }

    return $results;
}



function wpmem_clear_plugin_history_cache($plugin_path) {
    $cache_key = 'wpmem_plugin_history_' . md5($plugin_path);
    wp_cache_delete($cache_key);
}



add_action('wp_ajax_get_plugin_history', 'wpmem_get_plugin_history_ajax');
function wpmem_get_plugin_history_ajax() {
    check_ajax_referer('wp_memory_usage_nonce', 'nonce');
    if (!isset($_POST['plugin'])) {
        wp_send_json_error('Plugin not specified');
    }

    $plugin = sanitize_text_field(wp_unslash($_POST['plugin']));
    $history = wpmem_get_plugin_history($plugin);

    wp_send_json_success($history);
}








function wpmem_get_all_plugin_history() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wpmem_plugin_history';

    // Create a unique cache key for this query
    $cache_key = 'wpmem_all_plugin_history';

    // Try to get the results from cache
    $results = wp_cache_get($cache_key);

    // If the results are not in cache, query the database
    if (false === $results) {
        $results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            $wpdb->prepare(
                "SELECT plugin_path, memory_change, timestamp 
                FROM `" . esc_sql($table_name) . "` 
                WHERE plugin_path IN (SELECT DISTINCT plugin_path FROM `" . esc_sql($table_name) . "`)
                ORDER BY timestamp DESC
                -- %d",
                1
            )
        );

        // Cache the results for future use
        wp_cache_set($cache_key, $results, '', 3600); // Cache for 1 hour
    }

    // Process results...
    $history = array();
    foreach ($results as $row) {
        if (!isset($history[$row->plugin_path])) {
            $history[$row->plugin_path] = array();
        }
        if (count($history[$row->plugin_path]) < 5) {
            $history[$row->plugin_path][] = array(
                'memory_change' => $row->memory_change,
                'timestamp' => $row->timestamp
            );
        }
    }

    return $history;
}




function wpmem_clear_all_plugin_history_cache() {
    wp_cache_delete('wpmem_all_plugin_history');
}



function wpmem_clear_table_exists_cache() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wpmem_plugin_history';
    $cache_key = 'wpmem_table_exists_' . $table_name;
    wp_cache_delete($cache_key);
}

register_activation_hook(__FILE__, 'wpmem_clear_table_exists_cache');
register_deactivation_hook(__FILE__, 'wpmem_clear_table_exists_cache');







function wpmem_get_average_memory_usage($plugin_path) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'wpmem_plugin_history';
    
    // Create a unique cache key
    $cache_key = 'wpmem_avg_memory_' . md5($plugin_path);

    // Try to get the result from cache
    $avg_memory = wp_cache_get($cache_key);

    if (false === $avg_memory) {
        // Cache miss, perform the database query
        $result = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            $wpdb->prepare(
                "SELECT SUM(memory_change) as total_change, 
                        COUNT(*) as non_zero_count, 
                        SUM(zero_count) as zero_count
                FROM `" . esc_sql($table_name) . "`
                WHERE plugin_path = %s",
                $plugin_path
            )
        );
        
        if ($result) {
            $total_count = $result->non_zero_count + $result->zero_count;
            $avg_memory = $total_count > 0 ? ($result->total_change / $total_count) / (1024 * 1024) : 0;
            $avg_memory = round($avg_memory, 2); // Round to 2 decimal places
        } else {
            $avg_memory = 0;
        }

        // Cache the result for future use (cache for 5 minutes)
        wp_cache_set($cache_key, $avg_memory, '', 300);
    }
    
    return $avg_memory;
}



function wpmem_clear_average_memory_cache($plugin_path) {
    $cache_key = 'wpmem_avg_memory_' . md5($plugin_path);
    wp_cache_delete($cache_key);
}



add_action('wp_ajax_update_average_memory', 'wpmem_update_average_memory');
add_action('wp_ajax_nopriv_update_average_memory', 'wpmem_update_average_memory');

function wpmem_update_average_memory() {
    // Check nonce for security
    if (!isset($_POST['nonce'])) {
        wp_send_json_error('Security token not provided');
    }

    $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
    if (!wp_verify_nonce($nonce, 'wp_memory_usage_nonce')) {
        wp_send_json_error('Invalid security token');
    }

    if (!isset($_POST['plugin_path'])) {
        wp_send_json_error('Plugin path not provided');
    }

    $plugin_path = sanitize_text_field(wp_unslash($_POST['plugin_path']));
    $avg_memory = wpmem_get_average_memory_usage($plugin_path);

    wp_send_json_success(array('avg_memory' => $avg_memory));
}






function wpmem_add_increase_memory_button($content) {
    $wp_memory_limit = wp_convert_hr_to_bytes(WP_MEMORY_LIMIT);
    $current_memory_usage = memory_get_usage(true);
    
    if ($current_memory_usage > $wp_memory_limit) {
        $content .= '<button id="increase-memory-limit" class="button">Increase Memory Limit</button>';
        $content .= '<span id="memory-increase-result"></span>';
    }
    
    return $content;
}
add_filter('wpmem_memory_usage_content', 'wpmem_add_increase_memory_button');





function wpmem_increase_memory_limit() {
    check_ajax_referer('wp_memory_usage_nonce', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => 'Insufficient permissions'));
    }
    
    $current_limit = wp_convert_hr_to_bytes(WP_MEMORY_LIMIT);
    $new_limit = $current_limit * 2; // Double the current limit
    
    // Attempt to increase the limit
    if (wpmem_set_memory_limit($new_limit)) {
        wp_send_json_success(array('new_limit' => size_format($new_limit)));
    } else {
        wp_send_json_error(array('message' => 'Unable to increase memory limit. You may need to contact your hosting provider.'));
    }
}

add_action('wp_ajax_increase_memory_limit', 'wpmem_increase_memory_limit');

function wpmem_set_memory_limit($new_limit) {
    global $wp_filesystem;

    // Initialize the WP filesystem
    if (empty($wp_filesystem)) {
        require_once (ABSPATH . '/wp-admin/includes/file.php');
        WP_Filesystem();
    }

    $wp_config_file = ABSPATH . 'wp-config.php';
    $config_content = $wp_filesystem->get_contents($wp_config_file);
    
    if ($config_content === false) {
        return false;
    }
    
    $new_limit_formatted = size_format($new_limit);
    
    if (preg_match("/define\(\s*'WP_MEMORY_LIMIT',\s*'.*?'\s*\);/", $config_content)) {
        // WP_MEMORY_LIMIT is already defined, so update it
        $new_content = preg_replace(
            "/define\(\s*'WP_MEMORY_LIMIT',\s*'.*?'\s*\);/",
            "define('WP_MEMORY_LIMIT', '$new_limit_formatted');",
            $config_content
        );
    } else {
        // WP_MEMORY_LIMIT is not defined, so add it
        $new_content = preg_replace(
            "/<\?php/",
            "<?php\ndefine('WP_MEMORY_LIMIT', '$new_limit_formatted');",
            $config_content,
            1
        );
    }
    
    if ($wp_filesystem->put_contents($wp_config_file, $new_content) === false) {
        return false;
    }
    
    return true;
}






function wpmem_add_settings_link($links) {
    $settings_link = '<a href="' . admin_url('admin.php?page=wp_plugin_memory_usage') . '">Settings</a>';
    array_unshift($links, $settings_link);
    return $links;
}

$plugin = plugin_basename(__FILE__);
add_filter("plugin_action_links_$plugin", 'wpmem_add_settings_link');





?>
```
