options = get_option('aio_options', []);
// 1. WebP Auto Conversion (Background Processing)
if ( !empty($this->options['opt-perf-webp']) ) {
add_filter('wp_generate_attachment_metadata', [$this, 'schedule_webp_conversion'], 10, 2);
add_action('aio_convert_webp_cron', [$this, 'process_webp_conversion']);
}
// 2. Force Native Lazy Load
if ( !empty($this->options['opt-perf-lazyload']) ) {
add_filter( 'wp_lazy_loading_enabled', '__return_true' );
add_filter( 'the_content', [$this, 'force_lazy_load_content'], 99 );
}
// 3. Minify HTML/CSS/JS
if ( !empty($this->options['optEnableMinify']) ) {
add_action('template_redirect', [$this, 'start_minify_buffer'], 1);
}
// 4. Auto-Cleaner (Weekly DB Cleanup)
if ( !empty($this->options['optEnableAutoCleaner']) ) {
add_action('init', [$this, 'schedule_auto_cleaner']);
add_action('aio_weekly_db_cleanup', [$this, 'process_auto_cleaner']);
} else {
// Unschedule if disabled
$timestamp = wp_next_scheduled('aio_weekly_db_cleanup');
if ($timestamp) {
wp_unschedule_event($timestamp, 'aio_weekly_db_cleanup');
}
}
// 5. Auto Alt Tags
if ( !empty($this->options['optEnableAutoAltTags']) ) {
add_filter('wp_get_attachment_image_attributes', [$this, 'auto_fill_alt_tags'], 10, 3);
}
// 6. Media Replace
if ( !empty($this->options['optEnableMediaReplace']) ) {
add_filter('attachment_fields_to_edit', [$this, 'add_media_replace_field'], 10, 2);
add_action('edit_attachment', [$this, 'process_media_replace']);
}
}
/**
* Schedule the conversion to run asynchronously via WP Cron.
*/
public function schedule_webp_conversion($meta, $attachment_id) {
// Schedule event 5 seconds from now to avoid blocking the current upload request
if (!wp_next_scheduled('aio_convert_webp_cron', [$attachment_id])) {
wp_schedule_single_event(time() + 5, 'aio_convert_webp_cron', [$attachment_id]);
}
return $meta;
}
/**
* Process the WebP conversion in the background.
*/
public function process_webp_conversion($attachment_id) {
$delete_original = !empty($this->options['opt-perf-webp-delete-original']);
aio_generate_webp_for_attachment($attachment_id, $delete_original);
}
/**
* Fallback to add loading="lazy" to all img/iframe tags in content if missing.
*/
public function force_lazy_load_content($content) {
if (empty($content) || !is_string($content)) return $content;
// Add loading="lazy" to tags that don't have it
$content = preg_replace_callback(
'/<(img|iframe)[^>]+>/i',
function($matches) {
$tag = $matches[0];
if (stripos($tag, 'loading=') === false) {
$tag = str_replace('<' . $matches[1], '<' . $matches[1] . ' loading="lazy"', $tag);
}
return $tag;
},
$content
);
return $content;
}
/**
* Start Output Buffer for Minification
*/
public function start_minify_buffer() {
if (!is_admin() && !is_user_logged_in()) {
ob_start([$this, 'minify_html_output']);
}
}
/**
* Regex Minify Logic for HTML/CSS/JS
*/
public function minify_html_output($buffer) {
if (empty($buffer)) return $buffer;
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\/' // Remove HTML comments
);
$replace = array(
'>',
'<',
'\\1',
''
);
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
/**
* Schedule the Auto-Cleaner
*/
public function schedule_auto_cleaner() {
if (!wp_next_scheduled('aio_weekly_db_cleanup')) {
wp_schedule_event(time(), 'weekly', 'aio_weekly_db_cleanup');
}
}
/**
* Process DB Cleanup
*/
public function process_auto_cleaner() {
global $wpdb;
// Clean Post Revisions (keep last 5)
$wpdb->query("DELETE a,b,c FROM $wpdb->posts a LEFT JOIN $wpdb->term_relationships b ON (a.ID = b.object_id) LEFT JOIN $wpdb->postmeta c ON (a.ID = c.post_id) WHERE a.post_type = 'revision'");
// Clean Auto Drafts
$wpdb->query("DELETE a,b,c FROM $wpdb->posts a LEFT JOIN $wpdb->term_relationships b ON (a.ID = b.object_id) LEFT JOIN $wpdb->postmeta c ON (a.ID = c.post_id) WHERE a.post_status = 'auto-draft'");
// Clean Trashed Posts
$wpdb->query("DELETE a,b,c FROM $wpdb->posts a LEFT JOIN $wpdb->term_relationships b ON (a.ID = b.object_id) LEFT JOIN $wpdb->postmeta c ON (a.ID = c.post_id) WHERE a.post_status = 'trash'");
// Clean Spam Comments
$wpdb->query("DELETE FROM $wpdb->comments WHERE comment_approved = 'spam'");
// Clean Trashed Comments
$wpdb->query("DELETE FROM $wpdb->comments WHERE comment_approved = 'trash'");
// Clean Expired Transients
$time = time();
$wpdb->query("DELETE a, b FROM $wpdb->options a, $wpdb->options b WHERE a.option_name LIKE '\_transient\_%' AND a.option_name NOT LIKE '\_transient\_timeout\_%' AND b.option_name = CONCAT('_transient_timeout_', SUBSTRING(a.option_name, 12)) AND b.option_value < $time");
// Log to Audit Log if enabled
if (class_exists('AIO_Audit_Log') && method_exists('AIO_Audit_Log', 'insert_log')) {
// Need a way to call it statically or instance. Since it's private and tied to instance,
// we will just do a direct DB insert if we want, or skip it.
// Let's just skip it to keep it simple, or insert directly:
$table_name = $wpdb->prefix . 'aio_audit_logs';
$suppress = $wpdb->suppress_errors(true);
$wpdb->insert($table_name, [
'time' => current_time('mysql'),
'user_id' => 0,
'user_login' => 'System/Cron',
'event' => 'Auto-Cleaner',
'details' => 'Weekly database cleanup completed.',
'ip_address' => '127.0.0.1'
]);
$wpdb->suppress_errors($suppress);
}
}
/**
* Auto Fill Alt Tags
*/
public function auto_fill_alt_tags($attr, $attachment, $size) {
if (empty($attr['alt'])) {
$attr['alt'] = trim(strip_tags(get_the_title($attachment->ID)));
if (empty($attr['alt'])) {
// Fallback to parent post title
$parent_id = wp_get_post_parent_id($attachment->ID);
if ($parent_id) {
$attr['alt'] = trim(strip_tags(get_the_title($parent_id)));
}
}
}
return $attr;
}
/**
* Add Media Replace Field
*/
public function add_media_replace_field($form_fields, $post) {
// Only show in the traditional Edit Media screen
if (function_exists('get_current_screen')) {
$screen = get_current_screen();
if ($screen && $screen->id === 'attachment') {
$html = '
' . esc_html__('Upload a new file to replace the current one. Note: The old file will be deleted permanently.', 'aio') . '
'; $form_fields['aio_media_replace'] = array( 'label' => __('Replace File', 'aio'), 'input' => 'html', 'html' => $html ); } } return $form_fields; } /** * Process Media Replace Upload */ public function process_media_replace($attachment_id) { if (!empty($_FILES['aio_media_replace']['name'])) { require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); $uploaded_file = $_FILES['aio_media_replace']; $upload_overrides = array('test_form' => false); $old_file = get_attached_file($attachment_id); $movefile = wp_handle_upload($uploaded_file, $upload_overrides); if ($movefile && !isset($movefile['error'])) { // Delete old file if ($old_file && file_exists($old_file)) { @unlink($old_file); } $new_file = $movefile['file']; global $wpdb; $wpdb->update($wpdb->posts, ['post_mime_type' => $movefile['type'], 'guid' => $movefile['url']], ['ID' => $attachment_id] ); update_attached_file($attachment_id, $new_file); $attach_data = wp_generate_attachment_metadata($attachment_id, $new_file); wp_update_attachment_metadata($attachment_id, $attach_data); } } } } // Init Module new AIO_Optimizer(); if (!function_exists('aio_generate_webp_for_attachment')) { function aio_generate_webp_for_attachment($attachment_id, $delete_original = false) { $file_path = get_attached_file($attachment_id); if (!$file_path || !file_exists($file_path)) return false; $mime_type = mime_content_type($file_path); if (!in_array($mime_type, ['image/jpeg', 'image/png'])) { return false; // Only convert JPEG and PNG } $path_info = pathinfo($file_path); $webp_path = $path_info['dirname'] . '/' . $path_info['filename'] . '.webp'; $success = false; // Try raw GD first for maximum control over alpha and truecolor (fixes blank/white image bug) if (function_exists('imagewebp')) { $image = null; if ($mime_type === 'image/jpeg' && function_exists('imagecreatefromjpeg')) { $image = @imagecreatefromjpeg($file_path); } elseif ($mime_type === 'image/png' && function_exists('imagecreatefrompng')) { $image = @imagecreatefrompng($file_path); } if ($image) { if (function_exists('imagepalettetotruecolor')) { @imagepalettetotruecolor($image); } if ($mime_type === 'image/png') { @imagealphablending($image, false); @imagesavealpha($image, true); } $success = @imagewebp($image, $webp_path, 85); @imagedestroy($image); } } // Fallback to WP Image Editor if GD failed or is missing if (!$success || !file_exists($webp_path) || filesize($webp_path) < 100) { $editor = wp_get_image_editor($file_path); if (!is_wp_error($editor)) { $editor->set_quality(85); $saved = $editor->save($webp_path, 'image/webp'); $success = !is_wp_error($saved); } } if ($success && file_exists($webp_path) && filesize($webp_path) > 100) { // Update attachment file and mime type in DB update_attached_file($attachment_id, $webp_path); global $wpdb; $wpdb->update( $wpdb->posts, ['post_mime_type' => 'image/webp'], ['ID' => $attachment_id], ['%s'], ['%d'] ); // Delete original file if option is enabled if ( $delete_original ) { @unlink($file_path); } return true; } return false; } }