'.PLUGINMEMORYUSAGE_VERSION.'',
'pluginmemoryusage_display_memory_usage_dashboard'
);
}
// Hook to add the widget to the dashboard
add_action('wp_dashboard_setup', 'pluginmemoryusage_memory_usage_widget', 1);
// Get supported PHP versions with caching
function wpmem_get_supported_php_versions() {
$supported_versions = get_transient('wpmem_supported_php_versions');
if (false === $supported_versions) {
$response = wp_remote_get('https://www.php.net/supported-versions.php', array(
'sslverify' => false,
'timeout' => 5
));
if (!is_wp_error($response) && 200 === wp_remote_retrieve_response_code($response)) {
$html = wp_remote_retrieve_body($response);
$supported_versions = wpmem_parse_supported_versions($html);
set_transient('wpmem_supported_php_versions', $supported_versions, WEEK_IN_SECONDS);
}
}
return is_array($supported_versions) ? $supported_versions : [];
}
// Parse HTML response from PHP.net
function wpmem_parse_supported_versions($html) {
$versions = [];
$dom = new DOMDocument();
@$dom->loadHTML($html);
$tables = $dom->getElementsByTagName('table');
foreach ($tables as $table) {
$rows = $table->getElementsByTagName('tr');
foreach ($rows as $row) {
$cells = $row->getElementsByTagName('td');
if ($cells->length >= 5) {
$version = trim($cells->item(0)->textContent);
$eol_date = DateTime::createFromFormat('d M Y', trim($cells->item(3)->textContent));
if ($eol_date) {
$versions[$version] = [
'eol' => $eol_date->format('Y-m-d'),
'status' => (new DateTime() < $eol_date) ? 'supported' : 'eol'
];
}
}
}
}
return $versions;
}
function wpmem_get_php_status($current_version) {
$supported_versions = wpmem_get_supported_php_versions();
$current_branch = preg_replace('/^(\d+\.\d+).*$/', '$1', $current_version);
// Check if current branch is supported
foreach ($supported_versions as $version => $data) {
if (version_compare($current_branch, $version, '>=') && $data['status'] === 'supported') {
return 'supported';
}
}
return 'eol';
}
// to be shown in several places
function pluginmemoryusage_render_system_info() {
global $wpdb;
// Get PHP version and status
$php_version = phpversion();
$php_status = wpmem_get_php_status($php_version);
// Dashicons for PHP version status
$icons = [
'supported' => ' ',
'eol' => ' '
];
// Get latest PHP version (from transient)
$latest_php_version = get_transient('wpmem_latest_php_version');
if (!$latest_php_version) {
$latest_php_version = 'Unknown';
}
$is_latest = ($latest_php_version !== 'Unknown') ? version_compare($php_version, $latest_php_version, '>=') : false;
// Get MySQL version (with caching)
$mysql_version = wp_cache_get('wpmem_mysql_version');
if (false === $mysql_version) {
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- No WP API for MySQL version; safe, read-only query and result is cached.
$mysql_version = $wpdb->get_var("SELECT VERSION()");
wp_cache_set('wpmem_mysql_version', $mysql_version, '', 12 * HOUR_IN_SECONDS);
}
// Get max upload size
$max_upload = ini_get('upload_max_filesize');
$max_post = ini_get('post_max_size');
$memory_limit = ini_get('memory_limit');
$upload_mb = min(
wp_convert_hr_to_bytes($max_upload),
wp_convert_hr_to_bytes($max_post),
wp_convert_hr_to_bytes($memory_limit)
);
// Get WP and PHP memory limits
$wp_memory_limit = wp_convert_hr_to_bytes(WP_MEMORY_LIMIT);
$php_memory_limit = ini_get('memory_limit');
echo '
WordPress Version: ' . esc_html(get_bloginfo('version')) . '
';
echo 'PHP Version: ' . esc_html($php_version);
echo wp_kses_post($icons[$php_status]);
if ('Unknown' !== $latest_php_version) {
$label = $is_latest ? 'Latest' : 'Latest: ' . esc_html($latest_php_version);
$class = $is_latest ? 'php-version-latest' : 'php-version-outdated';
echo ' ' . esc_html($label) . ' ';
} else {
echo ' (Version check failed) ';
}
echo '
';
echo 'MySQL Version: ' . esc_html($mysql_version) . '
';
echo 'Max Upload Size: ' . esc_html(size_format($upload_mb)) . '
';
echo 'WordPress Memory Limit: ' . esc_html(size_format($wp_memory_limit)) . '
';
echo 'PHP Memory Limit: ' . esc_html($php_memory_limit) . '
';
}
// Function to display content in the dashboard widget
function pluginmemoryusage_display_memory_usage_dashboard() {
global $wpdb;
// Get WordPress memory limit
$wp_memory_limit = wp_convert_hr_to_bytes(WP_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 - In seperate function for reusability
pluginmemoryusage_render_system_info();
// Display memory usage
echo 'Current Memory Usage: ';
echo esc_html(size_format($current_memory_usage)) . ' of ' . esc_html(size_format($wp_memory_limit)) . '
';
echo '
' . esc_html(round($percentage_used, 1)) . '%
';
// 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 '
';
}
// Add button to Plugin Memory Control Panel
echo 'Plugin Memory Control Panel
';
}
function wpmem_memory_usage_admin_page() {
?>
Plugin Memory Usage - Control Panel
System Information
Current Memory Usage
Using of
Refresh Memory Usage
Memory fluctuate. Please press button once after entering panel.
$wp_memory_limit * 0.8) {
echo '
You are using more than 80% of allocated memory. Please click button below to try to increase memory limit.
';
echo '
Increase Memory Limit
';
echo '
';
} ?>
Memory Usage History
This plugin measures changes in WordPress memory usage as you activate and deactivate plugins. Here's how it works:
It records the current memory usage of WordPress.
When you activate or deactivate a plugin, it measures the memory usage again.
The difference between these measurements gives an estimate of the plugin's memory impact.
This process is repeated each time you toggle a plugin.
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.
To begin, try activating or deactivating plugins using the buttons provided. The memory usage history will appear here.
|
Plugins
';
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 '
';
echo '';
echo '
' . esc_html($plugin_data['Name']) . ' (' . esc_html($avg_memory) . ' MB) ';
echo '
';
echo '
';
echo '';
if ($is_memory_usage_plugin) {
echo 'Active ';
} else {
echo '';
echo $is_active ? 'Deactivate' : 'Activate';
echo ' ';
}
echo '
';
echo ' ';
}
echo '';
?>
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');
add_action('admin_enqueue_scripts', 'wp_memory_usage_enqueue_styles');
function wp_memory_usage_enqueue_styles($hook) {
// Load on all admin pages where the dashboard widget appears
wp_enqueue_style('wp-memory-usage-styles',
plugins_url('plugin-memory-usage.css', __FILE__),
array(),
filemtime(plugin_dir_path(__FILE__) . 'plugin-memory-usage.css')
);
}
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);
}
// Reset table verification cache when changing plugin state
register_activation_hook(__FILE__, 'wpmem_clear_table_exists_cache'); // Pre-activation check
register_deactivation_hook(__FILE__, 'wpmem_clear_table_exists_cache'); // Post-deactivation cleanup
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 .= 'Increase Memory Limit ';
$content .= ' ';
}
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);
// If current limit is 160MB or less, double it. Otherwise, increase by 25%.
if ($current_limit < 160 * 1024 * 1024) { // 160 MB in bytes
$new_limit = $current_limit * 2;
} else {
$new_limit = (int)($current_limit * 1.25); // Increase by 25%
}
// Optional: Cap the maximum limit to avoid runaway values (e.g., 512MB)
$max_limit = 512 * 1024 * 1024; // 512 MB in bytes
if ($new_limit > $max_limit) {
$new_limit = $max_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/",
"put_contents($wp_config_file, $new_content) === false) {
return false;
}
return true;
}
function wpmem_add_settings_link($links) {
$settings_link = 'Settings ';
array_unshift($links, $settings_link);
return $links;
}
$plugin = plugin_basename(__FILE__);
add_filter("plugin_action_links_$plugin", 'wpmem_add_settings_link');
function wpmem_add_memory_to_admin_bar($wp_admin_bar) {
$wp_memory_limit = wp_convert_hr_to_bytes(WP_MEMORY_LIMIT);
$current_memory_usage = memory_get_usage(true);
$percentage_used = round(($current_memory_usage / $wp_memory_limit) * 100, 1);
$wp_admin_bar->add_node(array(
'id' => 'wpmem_memory_usage',
'title' => 'MEM: ' . $percentage_used . '%',
'href' => admin_url('admin.php?page=wp_plugin_memory_usage'),
'meta' => array(
'title' => 'Current memory usage',
),
));
}
add_action('admin_bar_menu', 'wpmem_add_memory_to_admin_bar', 100);
?>