'image', 'jpeg' => 'image', 'png' => 'image', 'webp' => 'image', 'gif' => 'image', 'bmp' => 'image', 'tiff' => 'image', 'tif' => 'image', 'avif' => 'image', 'svg' => 'image', 'heic' => 'image', 'ico' => 'image', // pdf & documents 'pdf' => 'pdf', 'docx' => 'document', 'doc' => 'document', 'pptx' => 'document', 'ppt' => 'document', 'xlsx' => 'document', 'xls' => 'document', 'epub' => 'document', // audio / video / archive 'mp4' => 'video', 'mov' => 'video', 'webm' => 'video', 'mkv' => 'video', 'mp3' => 'audio', 'wav' => 'audio', 'flac' => 'audio', 'ogg' => 'audio', 'zip' => 'archive', ); if (!isset($map[$ext])) { return null; } $paths = array( 'image' => 'image-compressors', 'video' => 'video-compressors', 'audio' => 'audio-compressors', 'document' => 'document-compressors', 'pdf' => 'pdf-compressors', 'archive' => 'archive-compressors', ); return $paths[$map[$ext]]; } /** * Initialise and return the WP_Filesystem instance, or WP_Error when it is unavailable. */ function micompress_filesystem() { global $wp_filesystem; if (!function_exists('WP_Filesystem')) { require_once ABSPATH . 'wp-admin/includes/file.php'; } if (!WP_Filesystem() || !$wp_filesystem) { return new WP_Error('filesystem', __('The WordPress filesystem is not available.', 'micompress')); } return $wp_filesystem; } /** * Return the real path of an attachment file only if it lives inside the uploads * directory (resolved at runtime with wp_upload_dir()); otherwise WP_Error. */ function micompress_upload_path($attachment_id) { $path = get_attached_file($attachment_id); $real = $path ? realpath($path) : false; if (!$real || !is_file($real)) { return new WP_Error('missing', __('Attachment file not found.', 'micompress')); } $uploads = wp_upload_dir(null, false); $base = !empty($uploads['basedir']) ? realpath($uploads['basedir']) : false; if (!$base || strpos(wp_normalize_path($real), trailingslashit(wp_normalize_path($base))) !== 0) { return new WP_Error('location', __('Only files inside the uploads directory can be compressed.', 'micompress')); } return $real; } /** * Compress a local file via the MiCompress API. Returns the compressed bytes * (string) on success, or WP_Error on failure. */ function micompress_compress_path($path) { $fs = micompress_filesystem(); if (is_wp_error($fs)) { return $fs; } $contents = $fs->get_contents($path); if ($contents === false) { return new WP_Error('missing', __('File not found.', 'micompress')); } $endpoint = micompress_category_path($path); if (!$endpoint) { return new WP_Error('unsupported', __('Unsupported file type.', 'micompress')); } $preset = get_option('micompress_preset', 'recommended'); $url = MICOMPRESS_BASE_URL . '/' . $endpoint . '/compress'; $ua = 'micompress-wordpress/' . MICOMPRESS_VERSION . ' (+https://micompress.com)'; // Build the multipart body by hand so the request can go through the WordPress HTTP API. $boundary = 'micompress-' . wp_generate_password(24, false); $body = '--' . $boundary . "\r\n"; $body .= 'Content-Disposition: form-data; name="preset"' . "\r\n\r\n" . $preset . "\r\n"; $body .= '--' . $boundary . "\r\n"; $body .= 'Content-Disposition: form-data; name="file"; filename="' . str_replace('"', '', basename($path)) . '"' . "\r\n"; $body .= 'Content-Type: application/octet-stream' . "\r\n\r\n"; $body .= $contents . "\r\n"; $body .= '--' . $boundary . '--' . "\r\n"; $response = wp_remote_post($url, array( 'timeout' => 120, 'user-agent' => $ua, 'headers' => array( 'Accept' => 'application/json', 'Content-Type' => 'multipart/form-data; boundary=' . $boundary, ), 'body' => $body, )); if (is_wp_error($response)) { return $response; } $code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $json = json_decode($body, true); if (!is_array($json) || empty($json['success']) || empty($json['downloadUrl'])) { $msg = is_array($json) && !empty($json['error']) ? $json['error'] : ('HTTP ' . $code); return new WP_Error('api', $msg); } $download = wp_remote_get(MICOMPRESS_BASE_URL . $json['downloadUrl'], array( 'timeout' => 120, 'user-agent' => $ua, )); if (is_wp_error($download)) { return $download; } $bytes = wp_remote_retrieve_body($download); if ($bytes === '') { return new WP_Error('download', __('Empty download.', 'micompress')); } return $bytes; } /** * Replace an attachment's file with its compressed version and regenerate its metadata. * The file keeps its name so every URL already embedded in content keeps working; * only files inside the uploads directory are touched, via WP_Filesystem. * Returns saved-percent (int) on success or WP_Error. */ function micompress_compress_attachment($attachment_id) { $path = micompress_upload_path($attachment_id); if (is_wp_error($path)) { return $path; } $fs = micompress_filesystem(); if (is_wp_error($fs)) { return $fs; } $original = (int) $fs->size($path); $bytes = micompress_compress_path($path); if (is_wp_error($bytes)) { return $bytes; } // Only replace when the result is actually smaller. if (!$original || strlen($bytes) >= $original) { return 0; } if (!$fs->is_writable($path) || !$fs->put_contents($path, $bytes, FS_CHMOD_FILE)) { return new WP_Error('write', __('Could not write the compressed file.', 'micompress')); } if (!function_exists('wp_generate_attachment_metadata')) { require_once ABSPATH . 'wp-admin/includes/image.php'; } $meta = wp_generate_attachment_metadata($attachment_id, $path); if ($meta) { wp_update_attachment_metadata($attachment_id, $meta); } return (int) round((1 - strlen($bytes) / $original) * 100); } /* ------------------------------------------------------------------ * * Media Library row action * ------------------------------------------------------------------ */ add_filter('media_row_actions', 'micompress_row_action', 10, 2); function micompress_row_action($actions, $post) { if (current_user_can('upload_files') && micompress_category_path(get_attached_file($post->ID))) { $url = wp_nonce_url( admin_url('admin-post.php?action=micompress_compress&attachment=' . $post->ID), 'micompress_compress_' . $post->ID ); $actions['micompress'] = '' . esc_html__('Compress with MiCompress', 'micompress') . ''; } return $actions; } add_action('admin_post_micompress_compress', 'micompress_handle_single'); function micompress_handle_single() { $id = isset($_GET['attachment']) ? absint($_GET['attachment']) : 0; if (!$id || !current_user_can('upload_files') || !check_admin_referer('micompress_compress_' . $id)) { wp_die(esc_html__('Permission denied.', 'micompress')); } $result = micompress_compress_attachment($id); $status = is_wp_error($result) ? 'error' : 'ok'; $arg = is_wp_error($result) ? rawurlencode($result->get_error_message()) : (int) $result; wp_safe_redirect(add_query_arg(array('micompress' => $status, 'micompress_val' => $arg), admin_url('upload.php'))); exit; } /* ------------------------------------------------------------------ * * Bulk action * ------------------------------------------------------------------ */ add_filter('bulk_actions-upload', 'micompress_bulk_register'); function micompress_bulk_register($actions) { $actions['micompress_compress'] = __('Compress with MiCompress', 'micompress'); return $actions; } add_filter('handle_bulk_actions-upload', 'micompress_bulk_handle', 10, 3); function micompress_bulk_handle($redirect, $action, $ids) { if ($action !== 'micompress_compress' || !current_user_can('upload_files')) { return $redirect; } $done = 0; $failed = 0; foreach ($ids as $id) { $r = micompress_compress_attachment((int) $id); if (is_wp_error($r)) { $failed++; } else { $done++; } } return add_query_arg(array('micompress' => 'bulk', 'micompress_done' => $done, 'micompress_failed' => $failed), $redirect); } add_action('admin_notices', 'micompress_admin_notices'); function micompress_admin_notices() { // Display-only: these query args are set by our own redirects after the nonce-checked // actions above; they are sanitized here and never change any state. // phpcs:disable WordPress.Security.NonceVerification.Recommended if (!isset($_GET['micompress'])) { return; } $type = sanitize_key(wp_unslash($_GET['micompress'])); if ($type === 'ok') { $val = isset($_GET['micompress_val']) ? absint($_GET['micompress_val']) : 0; $msg = $val > 0 /* translators: %d: percentage of file size saved. */ ? sprintf(__('MiCompress: file compressed, saved %d%%.', 'micompress'), $val) : __('MiCompress: file already optimal, left unchanged.', 'micompress'); printf('

%s

', esc_html($msg)); } elseif ($type === 'bulk') { $done = isset($_GET['micompress_done']) ? absint($_GET['micompress_done']) : 0; $failed = isset($_GET['micompress_failed']) ? absint($_GET['micompress_failed']) : 0; printf( '

%s

', /* translators: 1: number of files compressed, 2: number of files that failed. */ esc_html(sprintf(__('MiCompress: %1$d compressed, %2$d failed.', 'micompress'), $done, $failed)) ); } elseif ($type === 'error') { $val = isset($_GET['micompress_val']) ? sanitize_text_field(wp_unslash($_GET['micompress_val'])) : ''; printf('

%s

', esc_html('MiCompress: ' . $val)); } // phpcs:enable WordPress.Security.NonceVerification.Recommended } /* ------------------------------------------------------------------ * * Settings page (Settings → MiCompress) * ------------------------------------------------------------------ */ add_action('admin_init', 'micompress_register_settings'); function micompress_register_settings() { register_setting('micompress', 'micompress_preset', array( 'type' => 'string', 'sanitize_callback' => 'micompress_sanitize_preset', 'default' => 'recommended', )); } function micompress_sanitize_preset($value) { return in_array($value, array('lossless', 'recommended', 'extreme'), true) ? $value : 'recommended'; } add_action('admin_menu', 'micompress_settings_menu'); function micompress_settings_menu() { add_options_page('MiCompress', 'MiCompress', 'manage_options', 'micompress', 'micompress_settings_page'); } function micompress_settings_page() { if (!current_user_can('manage_options')) { return; } $preset = get_option('micompress_preset', 'recommended'); ?>

MiCompress

micompress.com.