From 2b3e1a85a01a02161ee0eee5e04734861eae8978 Mon Sep 17 00:00:00 2001 From: Alejandro Date: Tue, 22 Sep 2026 20:26:57 -0600 Subject: [PATCH] =?UTF-8?q?a=C3=B1adir=20vista=20resumen,=20optimizador=20?= =?UTF-8?q?de=20archivos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- alcastromol-function.php | 11 +- functions/admin/modules-dashboard.php | 398 +++++++ functions/optimizer/optimizer.php | 1470 +++++++++++++++++++++++++ 3 files changed, 1878 insertions(+), 1 deletion(-) create mode 100644 functions/admin/modules-dashboard.php create mode 100644 functions/optimizer/optimizer.php diff --git a/alcastromol-function.php b/alcastromol-function.php index b5c6e58..7a64633 100644 --- a/alcastromol-function.php +++ b/alcastromol-function.php @@ -87,7 +87,7 @@ function alcastromol_check_oxygen() { if (alcastromol_get_oxygen_option() === '1' && !alcastromol_is_oxygen_installed()) { add_action('admin_notices', function () { echo '
-

Alcastromol Functions: Oxygen no está instalado. Tailwind v3 funciona de forma independiente. Puedes activar Oxygen más tarde desde Tailwind → Modo.

+

Alcastromol Functions: Oxygen no está instalado. Tailwind v3 funciona de forma independiente. Puedes activar Oxygen más tarde desde Centro de funciones → Tailwind v3.

'; }); } @@ -170,6 +170,15 @@ register_activation_hook(__FILE__, 'alcastromol_setup_general_settings'); register_deactivation_hook(__FILE__, 'alcastromol_cleanup_options'); +/* +|-------------------------------------------------------------------------- +| Centro de funciones +|-------------------------------------------------------------------------- +*/ + +alcastromol_require('functions/admin/modules-dashboard.php'); +alcastromol_require('functions/optimizer/optimizer.php'); + /* |-------------------------------------------------------------------------- | TailwindCSS diff --git a/functions/admin/modules-dashboard.php b/functions/admin/modules-dashboard.php new file mode 100644 index 0000000..1a9cda8 --- /dev/null +++ b/functions/admin/modules-dashboard.php @@ -0,0 +1,398 @@ + '1', + 'cache' => '1', + 'optimizer' => '0', + ]; + +} + +function alcastromol_get_modules() { + + $saved = get_option('alcastromol_modules', []); + + if (!is_array($saved)) { + $saved = []; + } + + return array_merge(alcastromol_default_modules(), $saved); + +} + +function alcastromol_is_module_active($module) { + + $modules = alcastromol_get_modules(); + + return isset($modules[$module]) && $modules[$module] === '1'; + +} + +function alcastromol_module_icon($name) { + + $icons = [ + 'tailwind' => '', + 'cache' => '', + 'optimizer' => '', + ]; + + return isset($icons[$name]) ? $icons[$name] : ''; + +} + +function alcastromol_get_module_cards() { + + return [ + 'tailwind' => [ + 'title' => 'Tailwind v3', + 'desc' => 'Carga Tailwind CSS v3 en el sitio. En desarrollo usa el CDN y en producción el CSS compilado, con la configuración del tema.', + 'settings' => admin_url('admin.php?page=alcastromol-tailwind-mode'), + 'bg' => '#e8f3ff', + 'color' => '#3b82f6', + 'icon' => 'tailwind', + 'badge' => '', + 'locked' => false, + ], + 'cache' => [ + 'title' => 'Cache de Tailwind', + 'desc' => 'Guarda el HTML del sitio para que Tailwind detecte las clases de páginas, entradas, productos, taxonomías y templates.', + 'settings' => admin_url('admin.php?page=tailwind-cache'), + 'bg' => '#f4e9ff', + 'color' => '#9333ea', + 'icon' => 'cache', + 'badge' => '', + 'locked' => false, + ], + 'optimizer' => [ + 'title' => 'Optimizador de archivos', + 'desc' => 'Detecta los CSS y JS del sitio. Puedes retirar su URL, agrupar el CSS crítico y el no crítico, juntar el JS en el header, o marcar data-nowprocket y media print.', + 'settings' => admin_url('admin.php?page=alcastromol-optimizer'), + 'bg' => '#e7f8ef', + 'color' => '#16a34a', + 'icon' => 'optimizer', + 'badge' => '', + 'locked' => false, + ], + ]; + +} + +add_action('admin_menu', function () { + + add_menu_page( + 'Centro de funciones', + 'Centro de funciones', + 'manage_options', + 'alcastromol-functions', + 'alcastromol_functions_dashboard_page', + 'dashicons-screenoptions', + 58 + ); + + add_submenu_page( + 'alcastromol-functions', + 'Centro de funciones', + 'Inicio', + 'manage_options', + 'alcastromol-functions', + 'alcastromol_functions_dashboard_page' + ); + +}, 9); + +add_action('wp_ajax_alcastromol_toggle_module', function () { + + if (!current_user_can('manage_options')) { + wp_send_json_error(['message' => 'No tienes permisos.'], 403); + } + + check_ajax_referer('alcastromol_toggle_module', 'nonce'); + + $module = sanitize_key($_POST['module'] ?? ''); + $active = ($_POST['active'] ?? '0') === '1' ? '1' : '0'; + $allowed = ['tailwind', 'cache', 'optimizer']; + + if (!in_array($module, $allowed, true)) { + wp_send_json_error(['message' => 'Esta función todavía no se puede activar.'], 400); + } + + $modules = alcastromol_get_modules(); + $modules[$module] = $active; + + update_option('alcastromol_modules', $modules); + + wp_send_json_success([ + 'module' => $module, + 'active' => $active, + ]); + +}); + +function alcastromol_functions_dashboard_page() { + + if (!current_user_can('manage_options')) { + return; + } + + $modules = alcastromol_get_modules(); + $cards = alcastromol_get_module_cards(); + $nonce = wp_create_nonce('alcastromol_toggle_module'); + + ?> +
+

Centro de funciones

+

Activa las funciones del plugin y abre sus ajustes.

+ +
+ $card) : ?> + +
+
+ +
+ +
+

+ + + + +

+

+
+ +
+ + Ajustes + + Ajustes + + + +
+
+ +
+
+ + + + + del header (crítico) +| o justo antes de (no crítico). +| 3. Agrupar el JS retirado en un \n"; + +} + +add_action('wp_head', 'alcastromol_optimizer_print_header_assets', PHP_INT_MAX); + +function alcastromol_optimizer_print_footer_assets() { + + if (!alcastromol_optimizer_is_active()) { + return; + } + + alcastromol_optimizer_print_style('alcastromol-optimizer-deferred', 'deferred.css'); + +} + +add_action('wp_footer', 'alcastromol_optimizer_print_footer_assets', PHP_INT_MAX); + +function alcastromol_optimizer_filter_link($tag) { + + $href = alcastromol_optimizer_tag_attr($tag, 'href'); + $rule = $href !== '' ? alcastromol_optimizer_rule_for_url($href) : null; + $rel = strtolower(alcastromol_optimizer_tag_attr($tag, 'rel')); + + if ($rule && !empty($rule['remove']) && (strpos($rel, 'stylesheet') !== false || strpos($rel, 'preload') !== false)) { + return ''; + } + + if (!$rule || empty($rule['async']) || strpos($rel, 'stylesheet') === false) { + return $tag; + } + + $tag = preg_replace('#\smedia=(["\']).*?\1#i', '', $tag); + $tag = preg_replace('#\sonload=(["\']).*?\1#i', '', $tag); + $tag = preg_replace('#\s*/?>\s*$#', '', $tag); + $async = $tag . ' media="print" onload="this.media=\'all\'">'; + $fallback = ''; + + return $async . $fallback; + +} + +function alcastromol_optimizer_filter_script($tag) { + + $src = alcastromol_optimizer_tag_attr($tag, 'src'); + + if ($src === '') { + return $tag; + } + + $rule = alcastromol_optimizer_rule_for_url($src); + + if (!$rule) { + return $tag; + } + + if (!empty($rule['remove'])) { + return ''; + } + + if (!empty($rule['nowprocket']) && stripos($tag, 'data-nowprocket') === false) { + return preg_replace('#]*>#is', function ($match) { + return alcastromol_optimizer_filter_link($match[0]); + }, $html); + + $html = preg_replace_callback('#]*\bsrc=(["\']).*?\1[^>]*>.*?#is', function ($match) { + return alcastromol_optimizer_filter_script($match[0]); + }, $html); + + return $html; + +} + +function alcastromol_optimizer_start_buffer() { + + if (!alcastromol_optimizer_is_active()) { + return; + } + + ob_start('alcastromol_optimizer_filter_html'); + +} + +add_action('template_redirect', 'alcastromol_optimizer_start_buffer', 100); + + +/* +|-------------------------------------------------------------------------- +| Admin +|-------------------------------------------------------------------------- +*/ + +add_action('admin_menu', function () { + + add_submenu_page( + 'alcastromol-functions', + 'Optimizador de archivos', + 'Optimizador', + 'manage_options', + 'alcastromol-optimizer', + 'alcastromol_optimizer_admin_page' + ); + +}, 21); + +add_action('admin_bar_menu', function ($bar) { + + if (!current_user_can('manage_options')) { + return; + } + + $bar->add_node([ + 'id' => 'alcastromol-optimizer', + 'parent' => 'alcastromol-tailwind', + 'title' => 'Optimizador de archivos', + 'href' => admin_url('admin.php?page=alcastromol-optimizer'), + ]); + +}, 91); + +function alcastromol_optimizer_notice($type, $message) { + + set_transient('alcastromol_optimizer_notice_' . get_current_user_id(), [ + 'type' => $type, + 'message' => $message, + ], MINUTE_IN_SECONDS); + +} + +function alcastromol_optimizer_redirect() { + + wp_safe_redirect(admin_url('admin.php?page=alcastromol-optimizer')); + exit; + +} + +add_action('admin_post_alcastromol_optimizer_scan', function () { + + if (!current_user_can('manage_options')) { + wp_die('No tienes permisos.'); + } + + check_admin_referer('alcastromol_optimizer_scan'); + + $scan = alcastromol_optimizer_scan(); + + if (is_wp_error($scan)) { + alcastromol_optimizer_notice('error', $scan->get_error_message()); + } else { + alcastromol_optimizer_notice( + 'success', + sprintf('Detección lista: %d CSS y %d JS en la portada.', count($scan['css']), count($scan['js'])) + ); + } + + alcastromol_optimizer_redirect(); + +}); + +function alcastromol_optimizer_posted_flag($row, $flag) { + + return !empty($row[$flag]); + +} + +add_action('admin_post_alcastromol_optimizer_save', function () { + + if (!current_user_can('manage_options')) { + wp_die('No tienes permisos.'); + } + + check_admin_referer('alcastromol_optimizer_save'); + + $scan = alcastromol_optimizer_get_scan(); + $known = []; + + foreach (['css', 'js'] as $type) { + foreach ((array) ($scan[$type] ?? []) as $asset) { + if (!empty($asset['key'])) { + $known[$asset['key']] = $asset; + } + } + } + + $posted = isset($_POST['assets']) && is_array($_POST['assets']) ? wp_unslash($_POST['assets']) : []; + $rules = alcastromol_optimizer_empty_rules(); + + foreach (['css', 'js'] as $type) { + foreach ((array) ($posted[$type] ?? []) as $key => $row) { + $key = sanitize_key($key); + + if (!isset($known[$key]) || !is_array($row)) { + continue; + } + + $remove = alcastromol_optimizer_posted_flag($row, 'remove'); + $critical = $type === 'css' && alcastromol_optimizer_posted_flag($row, 'critical'); + $deferred = $type === 'css' && alcastromol_optimizer_posted_flag($row, 'deferred'); + $bundle = $type === 'js' && alcastromol_optimizer_posted_flag($row, 'bundle'); + $async = $type === 'css' && alcastromol_optimizer_posted_flag($row, 'async'); + $nowprocket = $type === 'js' && alcastromol_optimizer_posted_flag($row, 'nowprocket'); + + if ($critical || $deferred || $bundle) { + $remove = true; + } + + if ($critical) { + $deferred = false; + $async = false; + } + + if ($deferred) { + $async = false; + } + + if ($bundle) { + $nowprocket = false; + } + + if ($async || $nowprocket) { + $remove = false; + $critical = false; + $deferred = false; + $bundle = false; + } + + if (!$remove && !$async && !$nowprocket) { + continue; + } + + $rules[$type][$key] = [ + 'key' => $key, + 'url' => $known[$key]['url'], + 'remove' => $remove, + 'critical' => $critical, + 'deferred' => $deferred, + 'bundle' => $bundle, + 'async' => $async, + 'nowprocket' => $nowprocket, + ]; + } + } + + $errors = alcastromol_optimizer_build_bundles($rules); + + if (is_wp_error($errors)) { + alcastromol_optimizer_notice('error', $errors->get_error_message()); + alcastromol_optimizer_redirect(); + } + + if ($errors) { + foreach ($errors as $url) { + foreach (['css', 'js'] as $type) { + foreach ($rules[$type] as $key => $rule) { + if ($rule['url'] === $url) { + $rules[$type][$key]['remove'] = false; + $rules[$type][$key]['critical'] = false; + $rules[$type][$key]['deferred'] = false; + $rules[$type][$key]['bundle'] = false; + } + } + } + } + } + + update_option(ALCASTROMOL_OPTIMIZER_RULES_OPTION, $rules, true); + + if ($errors) { + $errors = alcastromol_optimizer_build_bundles($rules); + } + + if (is_wp_error($errors)) { + alcastromol_optimizer_notice('error', $errors->get_error_message()); + } elseif ($errors) { + alcastromol_optimizer_notice('error', 'No se pudo leer algunos archivos, así que no se retiraron: ' . implode(', ', $errors)); + } else { + alcastromol_optimizer_notice('success', 'Optimización guardada.'); + } + + alcastromol_optimizer_redirect(); + +}); + +function alcastromol_optimizer_asset_label($asset) { + + if (!empty($asset['id'])) { + return preg_replace('/-(css|js)$/', '', $asset['id']); + } + + $path = wp_parse_url($asset['url'], PHP_URL_PATH); + + return $path ? basename($path) : $asset['url']; + +} + +/* +|-------------------------------------------------------------------------- +| Caché en .htaccess +|-------------------------------------------------------------------------- +*/ + +function alcastromol_optimizer_htaccess_file() { + + return ABSPATH . '.htaccess'; + +} + +function alcastromol_optimizer_htaccess_lines() { + + return [ + '', + ' ExpiresActive On', + ' ExpiresByType image/webp "access plus 1 year"', + ' ExpiresByType image/png "access plus 1 year"', + ' ExpiresByType image/svg+xml "access plus 1 year"', + ' ExpiresByType image/x-icon "access plus 1 year"', + ' ExpiresByType font/woff2 "access plus 1 year"', + ' ExpiresByType application/font-woff2 "access plus 1 year"', + ' ExpiresByType text/css "access plus 1 year"', + ' ExpiresByType application/javascript "access plus 1 year"', + ' ExpiresByType text/javascript "access plus 1 year"', + '', + '', + '', + ' ', + ' Header set Cache-Control "public, max-age=31536000, immutable"', + ' ', + ' ', + ' Header set Cache-Control "public, max-age=0, must-revalidate"', + ' ', + '', + ]; + +} + +function alcastromol_optimizer_htaccess_enabled() { + + $file = alcastromol_optimizer_htaccess_file(); + + if (!is_readable($file)) { + return false; + } + + $contents = file_get_contents($file); + + return is_string($contents) && str_contains($contents, '# BEGIN Alcastromol Cache'); + +} + +function alcastromol_optimizer_write_htaccess($enabled) { + + $file = alcastromol_optimizer_htaccess_file(); + + if (!file_exists($file) || !is_writable($file)) { + return new WP_Error('alcastromol_htaccess', 'No se puede escribir el archivo .htaccess.'); + } + + $contents = file_get_contents($file); + + if (!is_string($contents)) { + return new WP_Error('alcastromol_htaccess', 'No se pudo leer el archivo .htaccess.'); + } + + $start = '# BEGIN Alcastromol Cache'; + $end = '# END Alcastromol Cache'; + $lines = preg_split("/\r\n|\n|\r/", $contents); + $kept = []; + $inside = false; + + foreach ($lines as $line) { + if (!$inside && str_contains($line, $start)) { + $inside = true; + continue; + } + + if ($inside && str_contains($line, $end)) { + $inside = false; + continue; + } + + if (!$inside) { + $kept[] = $line; + } + } + + while ($kept && trim((string) end($kept)) === '') { + array_pop($kept); + } + + if ($enabled) { + $kept[] = ''; + $kept[] = $start; + foreach (alcastromol_optimizer_htaccess_lines() as $line) { + $kept[] = $line; + } + $kept[] = $end; + } + + $kept[] = ''; + + if (file_put_contents($file, implode("\n", $kept)) === false) { + return new WP_Error('alcastromol_htaccess', 'No se pudo guardar el archivo .htaccess.'); + } + + return true; + +} + +add_action('admin_post_alcastromol_optimizer_htaccess', function () { + + if (!current_user_can('manage_options')) { + wp_die('No tienes permisos.'); + } + + check_admin_referer('alcastromol_optimizer_htaccess'); + + $enabled = !empty($_POST['htaccess_cache']); + $result = alcastromol_optimizer_write_htaccess($enabled); + + if (is_wp_error($result)) { + alcastromol_optimizer_notice('error', $result->get_error_message()); + } elseif ($enabled) { + alcastromol_optimizer_notice('success', 'La caché de un año quedó escrita en .htaccess.'); + } else { + alcastromol_optimizer_notice('success', 'Se quitó la caché de .htaccess.'); + } + + alcastromol_optimizer_redirect(); + +}); + +function alcastromol_optimizer_admin_page() { + + if (!current_user_can('manage_options')) { + return; + } + + $scan = alcastromol_optimizer_get_scan(); + $rules = alcastromol_optimizer_get_rules(); + $notice = get_transient('alcastromol_optimizer_notice_' . get_current_user_id()); + + if ($notice) { + delete_transient('alcastromol_optimizer_notice_' . get_current_user_id()); + } + + $active = function_exists('alcastromol_is_module_active') && alcastromol_is_module_active('optimizer'); + + ?> +
+

Optimizador de archivos

+

+ Detecta los CSS y JS de la portada. En cada archivo eliges si se retira su URL, + si el CSS retirado entra al grupo crítico del header o al grupo no crítico de antes de </body>, + si el JS retirado entra al script global del header, si el script conserva data-nowprocket, + o si el CSS se carga con media="print" onload="this.media='all'". +

+ + +
+

El optimizador está apagado. Actívalo en Centro de funciones para aplicar estos cambios en el sitio.

+
+ + + +
+

+
+ + +
+

Caché en .htaccess

+

Imágenes, iconos, fuentes, CSS y JS se guardan un año. El HTML queda sin caché. El bloque se agrega al final de .htaccess y no modifica las reglas de WordPress ni las de WP Rocket.

+ +
+ + + +
+ + + Activa en .htaccess + +
+
+ +
+ + + + + + Última detección: + · + · CSS + · JS + + +
+ + +
+ + + + + + + +
+ +
+ + + + + +

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ArchivoRetirar URLQuita el link o el scriptCSS crítico<style> en el headerCSS no crítico<style> antes de </body>media="print"onload="this.media='all'"JS global<script> en el headerdata-nowprocketWP Rocket no lo procesa
+ + + +
+
+ 'Retirar URL', + 'critical' => 'CSS crítico en el header', + 'deferred' => 'CSS no crítico antes de cerrar body', + 'async' => 'media print', + 'bundle' => 'JS global en el header', + 'nowprocket' => 'data-nowprocket', + ]; + + ?> + + + > + +