Files
centro-de-funciones/functions/optimizer/optimizer.php
T

1471 lines
42 KiB
PHP

<?php
if (!defined('ABSPATH')) {
exit;
}
/*
|--------------------------------------------------------------------------
| Optimizador de archivos
|--------------------------------------------------------------------------
|
| Detecta los CSS y JS publicados en la portada y, por archivo, permite:
| 1. Retirar la URL original.
| 2. Agrupar el CSS retirado en un <style> del header (crítico)
| o justo antes de </body> (no crítico).
| 3. Agrupar el JS retirado en un <script> del header.
| 4. Agregar data-nowprocket al <script>.
| 5. Cargar el CSS con media="print" onload="this.media='all'".
|
*/
define('ALCASTROMOL_OPTIMIZER_SCAN_OPTION', 'alcastromol_optimizer_scan');
define('ALCASTROMOL_OPTIMIZER_RULES_OPTION', 'alcastromol_optimizer_rules');
function alcastromol_optimizer_empty_rules() {
return [
'css' => [],
'js' => [],
];
}
function alcastromol_optimizer_get_rules() {
$saved = get_option(ALCASTROMOL_OPTIMIZER_RULES_OPTION, []);
if (!is_array($saved)) {
return alcastromol_optimizer_empty_rules();
}
$rules = alcastromol_optimizer_empty_rules();
foreach (['css', 'js'] as $type) {
if (empty($saved[$type]) || !is_array($saved[$type])) {
continue;
}
foreach ($saved[$type] as $key => $rule) {
if (!is_array($rule) || empty($rule['url'])) {
continue;
}
$rules[$type][$key] = [
'key' => (string) $key,
'url' => (string) $rule['url'],
'remove' => !empty($rule['remove']),
'critical' => !empty($rule['critical']),
'deferred' => !empty($rule['deferred']),
'bundle' => !empty($rule['bundle']),
'async' => !empty($rule['async']),
'nowprocket' => !empty($rule['nowprocket']),
];
}
}
return $rules;
}
function alcastromol_optimizer_get_scan() {
$scan = get_option(ALCASTROMOL_OPTIMIZER_SCAN_OPTION, []);
if (!is_array($scan)) {
return [];
}
return $scan;
}
function alcastromol_optimizer_normalize_url($url, $base = '') {
$url = trim(html_entity_decode((string) $url, ENT_QUOTES));
if ($url === '' || stripos($url, 'data:') === 0 || stripos($url, 'javascript:') === 0) {
return '';
}
if (strpos($url, '//') === 0) {
$url = (is_ssl() ? 'https:' : 'http:') . $url;
} elseif ($base !== '' && !preg_match('#^https?://#i', $url)) {
$url = alcastromol_optimizer_resolve_url($url, $base);
} elseif (strpos($url, '/') === 0) {
$url = home_url($url);
}
$parts = wp_parse_url($url);
if (empty($parts['host']) || empty($parts['path'])) {
return '';
}
$query = [];
if (!empty($parts['query'])) {
parse_str($parts['query'], $query);
unset($query['ver']);
ksort($query);
}
$normalized = 'https://' . strtolower($parts['host']) . $parts['path'];
if ($query) {
$normalized .= '?' . http_build_query($query);
}
return $normalized;
}
function alcastromol_optimizer_resolve_url($url, $base) {
if (preg_match('#^https?://#i', $url) || strpos($url, '//') === 0) {
return $url;
}
$parts = wp_parse_url($base);
if (empty($parts['scheme']) || empty($parts['host'])) {
return $url;
}
$origin = $parts['scheme'] . '://' . $parts['host'];
if (!empty($parts['port'])) {
$origin .= ':' . $parts['port'];
}
if (strpos($url, '/') === 0) {
return $origin . $url;
}
$path = isset($parts['path']) ? $parts['path'] : '/';
$slash = strrpos($path, '/');
$dir = $slash === false ? '/' : substr($path, 0, $slash + 1);
return $origin . $dir . $url;
}
function alcastromol_optimizer_asset_key($url) {
$normalized = alcastromol_optimizer_normalize_url($url);
if ($normalized === '') {
return '';
}
return md5($normalized);
}
function alcastromol_optimizer_is_active() {
if (is_admin() || wp_doing_ajax() || wp_doing_cron()) {
return false;
}
if (defined('REST_REQUEST') && REST_REQUEST) {
return false;
}
if (is_feed() || is_embed() || is_customize_preview()) {
return false;
}
if (function_exists('alcastromol_is_module_active') && !alcastromol_is_module_active('optimizer')) {
return false;
}
if (function_exists('alcastromol_is_tailwind_builder_context') && alcastromol_is_tailwind_builder_context()) {
return false;
}
return true;
}
function alcastromol_optimizer_bundle_dir() {
$uploads = wp_upload_dir();
if (!empty($uploads['error'])) {
return '';
}
$dir = trailingslashit($uploads['basedir']) . 'alcastromol-optimizer';
if (!wp_mkdir_p($dir)) {
return '';
}
return $dir;
}
function alcastromol_optimizer_bundle_file($name) {
$dir = alcastromol_optimizer_bundle_dir();
if ($dir === '') {
return '';
}
return $dir . '/' . $name;
}
function alcastromol_optimizer_read_bundle($name) {
$file = alcastromol_optimizer_bundle_file($name);
if ($file === '' || !is_readable($file)) {
return '';
}
$contents = file_get_contents($file);
return is_string($contents) ? $contents : '';
}
/*
|--------------------------------------------------------------------------
| Detección
|--------------------------------------------------------------------------
*/
function alcastromol_optimizer_fetch_html($url) {
$args = [
'timeout' => 25,
'redirection' => 3,
'sslverify' => true,
'headers' => [
'Cache-Control' => 'no-cache',
],
];
$response = wp_remote_get($url, $args);
if (is_wp_error($response) && stripos($response->get_error_message(), 'ssl') !== false) {
$args['sslverify'] = false;
$response = wp_remote_get($url, $args);
}
if (is_wp_error($response)) {
return $response;
}
$code = (int) wp_remote_retrieve_response_code($response);
if ($code < 200 || $code >= 300) {
return new WP_Error('alcastromol_optimizer_http', 'La portada respondió HTTP ' . $code . '.');
}
$body = wp_remote_retrieve_body($response);
if (!is_string($body) || $body === '') {
return new WP_Error('alcastromol_optimizer_empty', 'La portada no devolvió HTML.');
}
return $body;
}
function alcastromol_optimizer_tag_attr($tag, $name) {
if (!preg_match('#\b' . preg_quote($name, '#') . '=(["\'])(.*?)\1#i', $tag, $match)) {
return '';
}
return html_entity_decode($match[2], ENT_QUOTES);
}
function alcastromol_optimizer_collect_asset(&$bucket, $url, $id, $base) {
$absolute = alcastromol_optimizer_resolve_url($url, $base);
$key = alcastromol_optimizer_asset_key($absolute);
if ($key === '' || isset($bucket[$key])) {
return;
}
$bucket[$key] = [
'key' => $key,
'url' => $absolute,
'id' => $id,
];
}
function alcastromol_optimizer_parse_html($html, $base) {
$css = [];
$js = [];
if (preg_match_all('#<link\b[^>]*>#is', $html, $links)) {
foreach ($links[0] as $tag) {
$href = alcastromol_optimizer_tag_attr($tag, 'href');
$rel = strtolower(alcastromol_optimizer_tag_attr($tag, 'rel'));
$type = strtolower(alcastromol_optimizer_tag_attr($tag, 'type'));
if ($href === '') {
continue;
}
$is_style = strpos($rel, 'stylesheet') !== false || strpos($type, 'text/css') !== false || preg_match('#\.css($|\?)#i', $href);
if (!$is_style || strpos($rel, 'preload') !== false || strpos($rel, 'icon') !== false) {
continue;
}
alcastromol_optimizer_collect_asset($css, $href, alcastromol_optimizer_tag_attr($tag, 'id'), $base);
}
}
if (preg_match_all('#<script\b[^>]*\bsrc=(["\']).*?\1[^>]*>#is', $html, $scripts)) {
foreach ($scripts[0] as $tag) {
$src = alcastromol_optimizer_tag_attr($tag, 'src');
if ($src === '') {
continue;
}
alcastromol_optimizer_collect_asset($js, $src, alcastromol_optimizer_tag_attr($tag, 'id'), $base);
}
}
return [
'css' => array_values($css),
'js' => array_values($js),
];
}
function alcastromol_optimizer_scan() {
$url = home_url('/');
$html = alcastromol_optimizer_fetch_html($url);
if (is_wp_error($html)) {
return $html;
}
$assets = alcastromol_optimizer_parse_html($html, $url);
$scan = [
'url' => $url,
'time' => time(),
'css' => $assets['css'],
'js' => $assets['js'],
];
update_option(ALCASTROMOL_OPTIMIZER_SCAN_OPTION, $scan, false);
return $scan;
}
/*
|--------------------------------------------------------------------------
| Lectura y agrupación
|--------------------------------------------------------------------------
*/
function alcastromol_optimizer_url_to_path($url) {
$path = wp_parse_url($url, PHP_URL_PATH);
if (!$path) {
return '';
}
$site_path = wp_parse_url(site_url('/'), PHP_URL_PATH);
$site_path = is_string($site_path) ? untrailingslashit($site_path) : '';
if ($site_path !== '' && strpos($path, $site_path) === 0) {
$path = substr($path, strlen($site_path));
}
$file = wp_normalize_path(ABSPATH . ltrim($path, '/'));
$root = wp_normalize_path(untrailingslashit(ABSPATH));
if (strpos($file, $root) !== 0 || !is_file($file) || !is_readable($file)) {
return '';
}
return $file;
}
function alcastromol_optimizer_is_fetchable($url) {
$url = esc_url_raw($url);
if ($url === '' || !wp_http_validate_url($url)) {
return false;
}
$host = wp_parse_url($url, PHP_URL_HOST);
$site = wp_parse_url(home_url(), PHP_URL_HOST);
if ($host && $site && strcasecmp($host, $site) === 0) {
return true;
}
if (filter_var($host, FILTER_VALIDATE_IP)) {
return (bool) filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
}
return stripos($url, 'https://') === 0;
}
function alcastromol_optimizer_get_contents($url) {
$path = alcastromol_optimizer_url_to_path($url);
if ($path !== '') {
$contents = file_get_contents($path);
return is_string($contents) ? $contents : '';
}
if (!alcastromol_optimizer_is_fetchable($url)) {
return new WP_Error('alcastromol_optimizer_url', 'URL no permitida.');
}
$response = wp_remote_get($url, [
'timeout' => 20,
'sslverify' => true,
]);
if (is_wp_error($response)) {
return $response;
}
$code = (int) wp_remote_retrieve_response_code($response);
if ($code < 200 || $code >= 300) {
return new WP_Error('alcastromol_optimizer_http', 'HTTP ' . $code);
}
return wp_remote_retrieve_body($response);
}
function alcastromol_optimizer_css_url($url) {
return str_replace(['\\', '"', "'", '(', ')', "\n", "\r"], '', $url);
}
function alcastromol_optimizer_rewrite_css_urls($css, $base) {
$css = preg_replace_callback('#url\(\s*([\'"]?)(.*?)\1\s*\)#i', function ($match) use ($base) {
$value = trim($match[2]);
if ($value === '' || stripos($value, 'data:') === 0 || strpos($value, '#') === 0 || preg_match('#^(https?:)?//#i', $value)) {
return $match[0];
}
return 'url("' . alcastromol_optimizer_css_url(alcastromol_optimizer_resolve_url($value, $base)) . '")';
}, $css);
$css = preg_replace_callback('#@import\s+(?:url\()?([\'"]?)([^\'")\s]+)\1#i', function ($match) use ($base) {
$value = $match[2];
if (preg_match('#^(https?:)?//#i', $value)) {
return $match[0];
}
return '@import url("' . alcastromol_optimizer_css_url(alcastromol_optimizer_resolve_url($value, $base)) . '")';
}, $css);
return is_string($css) ? $css : '';
}
function alcastromol_optimizer_sanitize_style($css) {
$css = preg_replace('/^\xEF\xBB\xBF/', '', $css);
return str_ireplace('</style', '<\\/style', $css);
}
function alcastromol_optimizer_sanitize_script($js) {
$js = preg_replace('/^\xEF\xBB\xBF/', '', $js);
return str_ireplace('</script', '<\\/script', $js);
}
function alcastromol_optimizer_write_bundle($name, $contents) {
$file = alcastromol_optimizer_bundle_file($name);
if ($file === '') {
return new WP_Error('alcastromol_optimizer_dir', 'No se pudo crear la carpeta de agrupación.');
}
if ($contents === '') {
if (file_exists($file)) {
wp_delete_file($file);
}
return true;
}
if (file_put_contents($file, $contents) === false) {
return new WP_Error('alcastromol_optimizer_write', 'No se pudo guardar ' . $name . '.');
}
return true;
}
function alcastromol_optimizer_build_bundles($rules) {
$groups = [
'critical.css' => [],
'deferred.css' => [],
'header.js' => [],
];
$errors = [];
foreach ($rules['css'] as $rule) {
if (empty($rule['remove'])) {
continue;
}
$target = '';
if (!empty($rule['critical'])) {
$target = 'critical.css';
} elseif (!empty($rule['deferred'])) {
$target = 'deferred.css';
}
if ($target === '') {
continue;
}
$contents = alcastromol_optimizer_get_contents($rule['url']);
if (is_wp_error($contents) || trim((string) $contents) === '') {
$errors[] = $rule['url'];
continue;
}
$groups[$target][] = "/* " . $rule['url'] . " */\n" . alcastromol_optimizer_sanitize_style(
alcastromol_optimizer_rewrite_css_urls($contents, $rule['url'])
);
}
foreach ($rules['js'] as $rule) {
if (empty($rule['remove']) || empty($rule['bundle'])) {
continue;
}
$contents = alcastromol_optimizer_get_contents($rule['url']);
if (is_wp_error($contents) || trim((string) $contents) === '') {
$errors[] = $rule['url'];
continue;
}
$groups['header.js'][] = "/* " . $rule['url'] . " */\n" . alcastromol_optimizer_sanitize_script($contents);
}
foreach ($groups as $name => $chunks) {
$written = alcastromol_optimizer_write_bundle($name, implode("\n\n", $chunks));
if (is_wp_error($written)) {
return $written;
}
}
return $errors;
}
/*
|--------------------------------------------------------------------------
| Front: retirar, agrupar y atributos
|--------------------------------------------------------------------------
*/
function alcastromol_optimizer_rule_map() {
static $map = null;
if ($map !== null) {
return $map;
}
$map = [];
$rules = alcastromol_optimizer_get_rules();
foreach (['css', 'js'] as $type) {
foreach ($rules[$type] as $rule) {
$map[$rule['key']] = $rule;
$map[$rule['key']]['type'] = $type;
}
}
return $map;
}
function alcastromol_optimizer_rule_for_url($url) {
$key = alcastromol_optimizer_asset_key($url);
if ($key === '') {
return null;
}
$map = alcastromol_optimizer_rule_map();
return isset($map[$key]) ? $map[$key] : null;
}
function alcastromol_optimizer_dequeue() {
if (!alcastromol_optimizer_is_active()) {
return;
}
global $wp_styles, $wp_scripts;
if ($wp_styles instanceof WP_Dependencies) {
foreach ((array) $wp_styles->queue as $handle) {
if (empty($wp_styles->registered[$handle]->src)) {
continue;
}
$rule = alcastromol_optimizer_rule_for_url($wp_styles->registered[$handle]->src);
if ($rule && !empty($rule['remove'])) {
wp_dequeue_style($handle);
}
}
}
if ($wp_scripts instanceof WP_Dependencies) {
foreach ((array) $wp_scripts->queue as $handle) {
if (empty($wp_scripts->registered[$handle]->src)) {
continue;
}
$rule = alcastromol_optimizer_rule_for_url($wp_scripts->registered[$handle]->src);
if ($rule && !empty($rule['remove'])) {
wp_dequeue_script($handle);
}
}
}
}
add_action('wp_print_styles', 'alcastromol_optimizer_dequeue', 0);
add_action('wp_print_scripts', 'alcastromol_optimizer_dequeue', 0);
add_action('wp_print_footer_scripts', 'alcastromol_optimizer_dequeue', 0);
function alcastromol_optimizer_print_style($id, $file) {
$css = alcastromol_optimizer_read_bundle($file);
if ($css === '') {
return;
}
echo '<style id="' . esc_attr($id) . '">' . $css . "</style>\n";
}
function alcastromol_optimizer_print_header_assets() {
if (!alcastromol_optimizer_is_active()) {
return;
}
alcastromol_optimizer_print_style('alcastromol-optimizer-critical', 'critical.css');
$js = alcastromol_optimizer_read_bundle('header.js');
if ($js === '') {
return;
}
echo '<script id="alcastromol-optimizer-header-js" data-nowprocket>' . $js . "</script>\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 = '<noscript>' . $tag . '></noscript>';
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('#<script\b#i', '<script data-nowprocket', $tag, 1);
}
return $tag;
}
function alcastromol_optimizer_filter_html($html) {
if (!is_string($html) || stripos($html, '<head') === false) {
return $html;
}
$html = preg_replace_callback('#<link\b[^>]*>#is', function ($match) {
return alcastromol_optimizer_filter_link($match[0]);
}, $html);
$html = preg_replace_callback('#<script\b[^>]*\bsrc=(["\']).*?\1[^>]*>.*?</script>#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 [
'<IfModule mod_expires.c>',
' 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"',
'</IfModule>',
'',
'<IfModule mod_headers.c>',
' <FilesMatch "\.(?:webp|png|svg|ico|woff2|css|js)$">',
' Header set Cache-Control "public, max-age=31536000, immutable"',
' </FilesMatch>',
' <FilesMatch "\.(?:html)$">',
' Header set Cache-Control "public, max-age=0, must-revalidate"',
' </FilesMatch>',
'</IfModule>',
];
}
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');
?>
<div class="wrap alcastromol-optimizer">
<h1>Optimizador de archivos</h1>
<p class="alcastromol-optimizer-intro">
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 <code>&lt;/body&gt;</code>,
si el JS retirado entra al script global del header, si el script conserva <code>data-nowprocket</code>,
o si el CSS se carga con <code>media="print" onload="this.media='all'"</code>.
</p>
<?php if (!$active) : ?>
<div class="notice notice-warning">
<p>El optimizador está apagado. Actívalo en Centro de funciones para aplicar estos cambios en el sitio.</p>
</div>
<?php endif; ?>
<?php if (is_array($notice) && !empty($notice['message'])) : ?>
<div class="notice notice-<?php echo $notice['type'] === 'error' ? 'error' : 'success'; ?> is-dismissible">
<p><?php echo esc_html($notice['message']); ?></p>
</div>
<?php endif; ?>
<section class="alcastromol-cache-box">
<h2>Caché en .htaccess</h2>
<p>Imágenes, iconos, fuentes, CSS y JS se guardan un año. El HTML queda sin caché. El bloque se agrega al final de <code>.htaccess</code> y no modifica las reglas de WordPress ni las de WP Rocket.</p>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<?php wp_nonce_field('alcastromol_optimizer_htaccess'); ?>
<input type="hidden" name="action" value="alcastromol_optimizer_htaccess">
<label class="alcastromol-cache-toggle">
<input type="checkbox" name="htaccess_cache" value="1" <?php checked(alcastromol_optimizer_htaccess_enabled()); ?>>
Habilitar estas declaraciones
</label>
<pre class="alcastromol-cache-rules"><?php echo esc_html(implode("\n", alcastromol_optimizer_htaccess_lines())); ?></pre>
<?php submit_button('Guardar caché', 'secondary', 'submit', false); ?>
<?php if (alcastromol_optimizer_htaccess_enabled()) : ?>
<span class="alcastromol-optimizer-meta">Activa en .htaccess</span>
<?php endif; ?>
</form>
</section>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<?php wp_nonce_field('alcastromol_optimizer_scan'); ?>
<input type="hidden" name="action" value="alcastromol_optimizer_scan">
<?php submit_button(empty($scan['css']) && empty($scan['js']) ? 'Detectar CSS y JS' : 'Volver a detectar', 'secondary', 'submit', false); ?>
<?php if (!empty($scan['time'])) : ?>
<span class="alcastromol-optimizer-meta">
Última detección: <?php echo esc_html(date_i18n('d/m/Y g:i a', $scan['time'])); ?>
· <?php echo esc_html($scan['url'] ?? home_url('/')); ?>
· <?php echo count((array) ($scan['css'] ?? [])); ?> CSS
· <?php echo count((array) ($scan['js'] ?? [])); ?> JS
</span>
<?php endif; ?>
</form>
<?php if (!empty($scan['css']) || !empty($scan['js'])) : ?>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" id="alcastromol-optimizer-form">
<?php wp_nonce_field('alcastromol_optimizer_save'); ?>
<input type="hidden" name="action" value="alcastromol_optimizer_save">
<?php alcastromol_optimizer_render_table('css', 'CSS', (array) $scan['css'], $rules['css']); ?>
<?php alcastromol_optimizer_render_table('js', 'JavaScript', (array) $scan['js'], $rules['js']); ?>
<?php submit_button('Guardar optimización'); ?>
</form>
<?php endif; ?>
</div>
<style>
.alcastromol-optimizer {
max-width: 1280px;
}
.alcastromol-optimizer-intro,
.alcastromol-optimizer-meta {
color: #646970;
}
.alcastromol-optimizer-meta {
margin-left: 12px;
}
.alcastromol-optimizer-section {
margin: 28px 0 10px;
}
.alcastromol-cache-box {
margin: 18px 0 28px;
padding: 18px 20px 8px;
background: #fff;
border: 1px solid #e7eaee;
border-radius: 10px;
}
.alcastromol-cache-box h2 {
margin: 0 0 8px;
}
.alcastromol-cache-box p {
margin-top: 0;
color: #646970;
}
.alcastromol-cache-toggle {
display: inline-flex;
align-items: center;
gap: 8px;
font-weight: 600;
}
.alcastromol-cache-rules {
margin: 14px 0;
padding: 14px 16px;
overflow: auto;
background: #f8f9fb;
border: 1px solid #e7eaee;
border-radius: 8px;
color: #1d2327;
font-size: 12px;
line-height: 1.5;
}
.alcastromol-opt-table {
width: 100%;
min-width: 880px;
border-collapse: collapse;
background: #fff;
}
.alcastromol-opt-scroll {
overflow-x: auto;
border: 1px solid #e7eaee;
border-radius: 8px;
background: #fff;
}
.alcastromol-opt-table th,
.alcastromol-opt-table td {
padding: 12px;
border-bottom: 1px solid #eef0f3;
vertical-align: middle;
}
.alcastromol-opt-table th {
font-size: 12px;
line-height: 1.35;
text-align: left;
background: #f8f9fb;
}
.alcastromol-opt-table th span {
display: block;
margin-top: 6px;
color: #646970;
font-weight: 400;
}
.alcastromol-opt-table th.alcastromol-opt-check,
.alcastromol-opt-table td.alcastromol-opt-check {
width: 140px;
text-align: center;
}
.alcastromol-opt-name {
font-weight: 600;
}
.alcastromol-opt-url {
display: block;
margin-top: 4px;
color: #646970;
font-size: 12px;
line-height: 1.4;
word-break: break-all;
}
.alcastromol-opt-table tr:last-child td {
border-bottom: 0;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function () {
var form = document.getElementById('alcastromol-optimizer-form');
if (!form) {
return;
}
function field(row, name) {
return row.querySelector('[data-opt="' + name + '"]');
}
function uncheck(row, names) {
names.forEach(function (name) {
var input = field(row, name);
if (input) {
input.checked = false;
}
});
}
form.addEventListener('change', function (event) {
var input = event.target;
if (!input.dataset || !input.dataset.opt) {
return;
}
var row = input.closest('tr');
var opt = input.dataset.opt;
if (!input.checked) {
if (opt === 'remove') {
uncheck(row, ['critical', 'deferred', 'bundle']);
}
return;
}
if (opt === 'critical' || opt === 'deferred' || opt === 'bundle') {
var remove = field(row, 'remove');
if (remove) {
remove.checked = true;
}
if (opt === 'critical') {
uncheck(row, ['deferred', 'async']);
}
if (opt === 'deferred') {
uncheck(row, ['critical', 'async']);
}
if (opt === 'bundle') {
uncheck(row, ['nowprocket']);
}
}
if (opt === 'async') {
uncheck(row, ['remove', 'critical', 'deferred']);
}
if (opt === 'nowprocket') {
uncheck(row, ['remove', 'bundle']);
}
});
});
</script>
<?php
}
function alcastromol_optimizer_render_table($type, $title, $assets, $rules) {
?>
<h2 class="alcastromol-optimizer-section"><?php echo esc_html($title); ?></h2>
<div class="alcastromol-opt-scroll">
<table class="alcastromol-opt-table">
<thead>
<tr>
<th>Archivo</th>
<th class="alcastromol-opt-check">Retirar URL<span>Quita el link o el script</span></th>
<?php if ($type === 'css') : ?>
<th class="alcastromol-opt-check">CSS crítico<span>&lt;style&gt; en el header</span></th>
<th class="alcastromol-opt-check">CSS no crítico<span>&lt;style&gt; antes de &lt;/body&gt;</span></th>
<th class="alcastromol-opt-check">media="print"<span>onload="this.media='all'"</span></th>
<?php else : ?>
<th class="alcastromol-opt-check">JS global<span>&lt;script&gt; en el header</span></th>
<th class="alcastromol-opt-check">data-nowprocket<span>WP Rocket no lo procesa</span></th>
<?php endif; ?>
</tr>
</thead>
<tbody>
<?php foreach ($assets as $asset) : ?>
<?php $rule = $rules[$asset['key']] ?? []; ?>
<tr>
<td>
<span class="alcastromol-opt-name"><?php echo esc_html(alcastromol_optimizer_asset_label($asset)); ?></span>
<code class="alcastromol-opt-url"><?php echo esc_html($asset['url']); ?></code>
<input type="hidden" name="assets[<?php echo esc_attr($type); ?>][<?php echo esc_attr($asset['key']); ?>][url]" value="<?php echo esc_url($asset['url']); ?>">
</td>
<?php alcastromol_optimizer_render_check($type, $asset['key'], 'remove', !empty($rule['remove'])); ?>
<?php if ($type === 'css') : ?>
<?php alcastromol_optimizer_render_check($type, $asset['key'], 'critical', !empty($rule['critical'])); ?>
<?php alcastromol_optimizer_render_check($type, $asset['key'], 'deferred', !empty($rule['deferred'])); ?>
<?php alcastromol_optimizer_render_check($type, $asset['key'], 'async', !empty($rule['async'])); ?>
<?php else : ?>
<?php alcastromol_optimizer_render_check($type, $asset['key'], 'bundle', !empty($rule['bundle'])); ?>
<?php alcastromol_optimizer_render_check($type, $asset['key'], 'nowprocket', !empty($rule['nowprocket'])); ?>
<?php endif; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
function alcastromol_optimizer_render_check($type, $key, $opt, $checked) {
$labels = [
'remove' => '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',
];
?>
<td class="alcastromol-opt-check">
<input
type="checkbox"
data-opt="<?php echo esc_attr($opt); ?>"
name="assets[<?php echo esc_attr($type); ?>][<?php echo esc_attr($key); ?>][<?php echo esc_attr($opt); ?>]"
value="1"
aria-label="<?php echo esc_attr($labels[$opt] ?? $opt); ?>"
<?php checked($checked); ?>
>
</td>
<?php
}