Files
2026-09-28 18:31:15 -06:00

1713 lines
51 KiB
PHP

<?php
if (!defined('ABSPATH')) exit;
/*
|--------------------------------------------------------------------------
| Configuración general
|--------------------------------------------------------------------------
*/
define('ALCASTROMOL_TAILWIND_MODE_OPTION', 'alcastromol_tailwind_mode');
define('ALCASTROMOL_TAILWIND_CSS_OUTPUT_OPTION', 'alcastromol_tailwind_css_output');
define('ALCASTROMOL_TAILWIND_SETTINGS_OPTION', 'alcastromol_tailwind_settings');
define('ALCASTROMOL_TAILWIND_BASE_DIR', plugin_dir_path(__DIR__) . 'tailwindcss/');
define('ALCASTROMOL_TAILWIND_BASE_URL', plugin_dir_url(__DIR__) . 'tailwindcss/');
define('ALCASTROMOL_TAILWIND_INPUT_CSS', ALCASTROMOL_TAILWIND_BASE_DIR . 'css-dev/input.css');
define('ALCASTROMOL_TAILWIND_OUTPUT_CSS', ALCASTROMOL_TAILWIND_BASE_DIR . 'css-production/styles-tailwind.css');
define('ALCASTROMOL_TAILWIND_CONFIG', ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwind.config.js');
/*
|--------------------------------------------------------------------------
| Configuración default de Tailwind
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_default_settings() {
return [
'content' => alcastromol_tailwind_default_content_paths(),
'theme' => [
'screens' => [
'xxxxl' => [ 'max' => '1701px' ],
'xxxl' => [ 'max' => '1550px' ],
'xxl' => [ 'max' => '1439px' ],
'xl' => [ 'max' => '1119px' ],
'lg' => [ 'max' => '1024px' ],
'md' => [ 'max' => '767px' ],
'sm' => [ 'max' => '479px' ],
'ssm' => [ 'max' => '380px' ],
],
'container' => [
'center' => true,
'padding' => '1rem',
'screens' => [
'DEFAULT' => '1702px',
],
],
'extend' => [
'colors' => [
'color' => [
'1' => '#004983',
'2' => '#333333',
'3' => '#B0B0B0',
],
'tva' => [
'red' => '#E30613',
'burgundy' => '#B8405C',
'ink' => '#1A1A1A',
'muted' => '#6B6B6B',
'line' => '#E6E6E6',
'soft' => '#F5F5F5',
],
],
'fontFamily' => [
'sans' => ['Inter', 'sans-serif'],
],
],
],
'plugins' => [],
];
}
/*
|--------------------------------------------------------------------------
| Rutas content de Tailwind
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_theme_content_paths() {
$paths = [];
$stylesheet = wp_normalize_path(get_stylesheet_directory());
$template = wp_normalize_path(get_template_directory());
if ($stylesheet) {
$paths[] = $stylesheet . '/**/*.{php,html,js}';
}
if ($template && $template !== $stylesheet) {
$paths[] = $template . '/**/*.{php,html,js}';
}
return array_values(array_unique($paths));
}
function alcastromol_tailwind_default_content_paths() {
$paths = [
'./cache/*.{php,html,js}',
];
if (!alcastromol_is_oxygen_enabled()) {
$paths = array_merge($paths, alcastromol_tailwind_theme_content_paths());
}
return array_values(array_unique($paths));
}
function alcastromol_tailwind_compile_content_paths($content) {
if (!is_array($content)) {
$content = [];
}
if (!alcastromol_is_oxygen_enabled()) {
$content = array_merge($content, alcastromol_tailwind_theme_content_paths());
}
return array_values(array_unique(array_filter($content)));
}
/*
|--------------------------------------------------------------------------
| Obtener configuración de Tailwind
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_get_settings() {
$defaults = alcastromol_tailwind_default_settings();
$settings = get_option(ALCASTROMOL_TAILWIND_SETTINGS_OPTION, []);
if (!is_array($settings)) {
$settings = [];
}
$settings = wp_parse_args($settings, $defaults);
if (empty($settings['content']) || !is_array($settings['content'])) {
$settings['content'] = $defaults['content'];
}
if (empty($settings['theme']) || !is_array($settings['theme'])) {
$settings['theme'] = $defaults['theme'];
}
if (!isset($settings['plugins']) || !is_array($settings['plugins'])) {
$settings['plugins'] = [];
}
return $settings;
}
/*
|--------------------------------------------------------------------------
| Generar archivo tailwind.config.js
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_generate_config_file() {
$settings = alcastromol_tailwind_get_settings();
$config = [
'content' => alcastromol_tailwind_compile_content_paths($settings['content']),
'theme' => $settings['theme'],
'plugins' => $settings['plugins'],
];
$json = wp_json_encode(
$config,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
if (!$json) {
return [
'success' => false,
'message' => 'No se pudo convertir la configuración de Tailwind a JSON.',
];
}
$js = "/** @type {import('tailwindcss').Config} */\n";
$js .= "module.exports = " . $json . ";\n";
$config_dir = dirname(ALCASTROMOL_TAILWIND_CONFIG);
if (!file_exists($config_dir)) {
wp_mkdir_p($config_dir);
}
if (!is_dir($config_dir) || !is_writable($config_dir)) {
return [
'success' => false,
'message' => 'La carpeta del archivo tailwind.config.js no existe o no tiene permisos de escritura: ' . $config_dir,
];
}
$written = file_put_contents(ALCASTROMOL_TAILWIND_CONFIG, $js);
if ($written === false) {
return [
'success' => false,
'message' => 'No se pudo escribir el archivo tailwind.config.js.',
];
}
clearstatcache(true, ALCASTROMOL_TAILWIND_CONFIG);
return [
'success' => true,
'message' => 'tailwind.config.js generado correctamente.',
'file' => ALCASTROMOL_TAILWIND_CONFIG,
'size' => file_exists(ALCASTROMOL_TAILWIND_CONFIG) ? size_format(filesize(ALCASTROMOL_TAILWIND_CONFIG)) : '',
];
}
/*
|--------------------------------------------------------------------------
| Obtener modo actual
|--------------------------------------------------------------------------
*/
function alcastromol_get_tailwind_mode() {
$mode = get_option(ALCASTROMOL_TAILWIND_MODE_OPTION, 'production');
if (!in_array($mode, ['developer', 'production'], true)) {
$mode = 'production';
}
return $mode;
}
/*
|--------------------------------------------------------------------------
| Forma de salida del CSS productivo: archivo .css o <style> en el header
|--------------------------------------------------------------------------
*/
function alcastromol_get_tailwind_css_output() {
$output = get_option(ALCASTROMOL_TAILWIND_CSS_OUTPUT_OPTION, 'file');
if (!in_array($output, ['file', 'inline'], true)) {
$output = 'file';
}
return $output;
}
function alcastromol_is_tailwind_css_inline() {
return alcastromol_get_tailwind_css_output() === 'inline';
}
function alcastromol_get_compiled_tailwind_css() {
$path = ALCASTROMOL_TAILWIND_OUTPUT_CSS;
if (!file_exists($path) || !is_readable($path)) {
return '';
}
$css = file_get_contents($path);
if ($css === false) {
return '';
}
return str_replace('</style', '<\/style', $css);
}
function alcastromol_get_tailwind_head_markup() {
$css_path = ALCASTROMOL_TAILWIND_OUTPUT_CSS;
if (!file_exists($css_path)) {
return '';
}
if (alcastromol_is_tailwind_css_inline()) {
$css = alcastromol_get_compiled_tailwind_css();
if ($css === '') {
return '';
}
return '<style id="alcastromol-tailwind-css">' . $css . '</style>' . "\n";
}
$css_url = ALCASTROMOL_TAILWIND_BASE_URL . 'css-production/styles-tailwind.css';
$version = filemtime($css_path);
return sprintf(
'<link rel="stylesheet" id="alcastromol-tailwind-css" href="%s" media="all" />' . "\n",
esc_url($css_url . '?ver=' . $version)
);
}
function alcastromol_tailwind_strip_css_from_html($html) {
$replacements = [
'#<link[^>]+id=["\']alcastromol-tailwind-css["\'][^>]*>\s*#i',
'#<link[^>]+href=["\'][^"\']*/tailwindcss/css-production/styles-tailwind\.css[^"\']*["\'][^>]*>\s*#i',
'#<style[^>]*id=["\']alcastromol-tailwind-css["\'][^>]*>.*?</style>\s*#is',
];
foreach ($replacements as $pattern) {
$stripped = preg_replace($pattern, '', $html);
if ($stripped !== null) {
$html = $stripped;
}
}
return $html;
}
/*
|--------------------------------------------------------------------------
| Validar si está en modo developer
|--------------------------------------------------------------------------
*/
function alcastromol_is_tailwind_developer_mode() {
return alcastromol_get_tailwind_mode() === 'developer';
}
/*
|--------------------------------------------------------------------------
| Detectar si la URL actual contiene algún parámetro del builder
|--------------------------------------------------------------------------
*/
function alcastromol_request_has_builder_param($params) {
foreach ($params as $param) {
if (isset($_GET[$param]) || isset($_POST[$param]) || isset($_REQUEST[$param])) {
return true;
}
}
return false;
}
/*
|--------------------------------------------------------------------------
| Detectar Oxygen Builder
|--------------------------------------------------------------------------
*/
function alcastromol_is_oxygen_builder() {
if (!alcastromol_is_oxygen_enabled()) {
return false;
}
$oxygen_params = [
'ct_builder',
'ct_inner',
'oxygen_iframe',
'oxygen_builder',
'ct_sign_sha256',
'ct_template',
];
if (alcastromol_request_has_builder_param($oxygen_params)) {
return true;
}
$request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
if (
strpos($request_uri, 'ct_builder') !== false ||
strpos($request_uri, 'ct_inner') !== false ||
strpos($request_uri, 'oxygen_iframe') !== false ||
strpos($request_uri, 'oxygen_builder') !== false
) {
return true;
}
return false;
}
/*
|--------------------------------------------------------------------------
| Detectar Breakdance Builder
|--------------------------------------------------------------------------
*/
function alcastromol_is_breakdance_builder() {
$breakdance_params = [
'breakdance',
'breakdance_builder',
'breakdance_iframe',
'breakdance_preview',
'breakdance_open',
'breakdance_canvas',
'breakdance_editor',
];
if (alcastromol_request_has_builder_param($breakdance_params)) {
return true;
}
$request_uri = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])) : '';
if (
strpos($request_uri, 'breakdance') !== false ||
strpos($request_uri, 'breakdance_builder') !== false ||
strpos($request_uri, 'breakdance_iframe') !== false ||
strpos($request_uri, 'breakdance_preview') !== false
) {
return true;
}
return false;
}
/*
|--------------------------------------------------------------------------
| Detectar contexto de builder para Tailwind
|--------------------------------------------------------------------------
*/
function alcastromol_is_tailwind_builder_context() {
if (alcastromol_is_oxygen_builder()) {
return true;
}
if (alcastromol_is_breakdance_builder()) {
return true;
}
return false;
}
/*
|--------------------------------------------------------------------------
| Generar HTML del CDN Tailwind con configuración dinámica
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_cdn_script_html() {
$settings = alcastromol_tailwind_get_settings();
/*
* Para el CDN solo usamos theme.
* content no aplica porque el CDN genera clases en el navegador.
*/
$cdn_config = [
'theme' => $settings['theme'],
];
ob_start();
?>
<!-- Tailwind CDN -->
<!--! En sitios productivos no debería estar el CDN, sino el CSS compilado -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
window.tailwind = window.tailwind || {};
window.tailwind.config = <?php echo wp_json_encode($cdn_config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>;
</script>
<?php
return ob_get_clean();
}
function alcastromol_tailwind_module_is_active() {
if (!function_exists('alcastromol_is_module_active')) {
return true;
}
return alcastromol_is_module_active('tailwind');
}
/*
|--------------------------------------------------------------------------
| Imprimir CDN Tailwind
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_cdn_script() {
if (!alcastromol_tailwind_module_is_active()) {
return;
}
static $loaded = false;
if ($loaded) {
return;
}
$loaded = true;
echo alcastromol_tailwind_cdn_script_html();
}
/*
|--------------------------------------------------------------------------
| Cargar Tailwind CSS compilado en front end normal
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_loader() {
if (!alcastromol_tailwind_module_is_active()) {
return;
}
/*
* Nunca cargar CSS compilado en wp-admin.
*/
if (is_admin()) {
return;
}
/*
* Si estamos dentro de Oxygen o Breakdance,
* no cargamos el CSS compilado porque ahí debe cargar el CDN.
*/
if (alcastromol_is_tailwind_builder_context()) {
return;
}
/*
* En modo developer, el front end usa CDN.
*/
if (alcastromol_is_tailwind_developer_mode()) {
return;
}
$css_path = ALCASTROMOL_TAILWIND_OUTPUT_CSS;
$css_url = ALCASTROMOL_TAILWIND_BASE_URL . 'css-production/styles-tailwind.css';
if (!file_exists($css_path)) {
return;
}
if (alcastromol_is_tailwind_css_inline()) {
return;
}
wp_enqueue_style(
'alcastromol-tailwind',
$css_url,
[],
filemtime($css_path)
);
}
add_action('wp_enqueue_scripts', 'alcastromol_tailwind_loader', PHP_INT_MAX);
function alcastromol_tailwind_print_inline_css() {
if (!alcastromol_tailwind_module_is_active()) {
return;
}
if (is_admin()) {
return;
}
if (alcastromol_is_tailwind_builder_context()) {
return;
}
if (alcastromol_is_tailwind_developer_mode()) {
return;
}
if (!alcastromol_is_tailwind_css_inline()) {
return;
}
echo alcastromol_get_tailwind_head_markup();
}
add_action('wp_head', 'alcastromol_tailwind_print_inline_css', PHP_INT_MAX);
/*
|--------------------------------------------------------------------------
| Forzar Tailwind CSS como último CSS real antes de cerrar </head>
|--------------------------------------------------------------------------
|
| Oxygen puede imprimir sus HEADER ASSETS después de la cola normal de
| WordPress. Por eso PHP_INT_MAX en wp_enqueue_scripts no siempre basta.
| Este buffer elimina la impresión previa del CSS productivo y lo inserta
| justo antes de </head>, dejando Tailwind como el último CSS del header.
|
*/
function alcastromol_tailwind_start_head_buffer() {
if (!alcastromol_tailwind_module_is_active()) {
return;
}
if (is_admin()) {
return;
}
if (alcastromol_is_tailwind_builder_context()) {
return;
}
if (alcastromol_is_tailwind_developer_mode()) {
return;
}
if (!file_exists(ALCASTROMOL_TAILWIND_OUTPUT_CSS)) {
return;
}
ob_start('alcastromol_tailwind_move_css_before_head_close');
}
add_action('template_redirect', 'alcastromol_tailwind_start_head_buffer', 0);
function alcastromol_tailwind_move_css_before_head_close($html) {
if (!is_string($html) || stripos($html, '</head>') === false) {
return $html;
}
$markup = alcastromol_get_tailwind_head_markup();
if ($markup === '') {
return $html;
}
$html = alcastromol_tailwind_strip_css_from_html($html);
return str_ireplace('</head>', $markup . '</head>', $html);
}
/*
|--------------------------------------------------------------------------
| Cargar CDN en front end normal solo en modo Developer
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_front_cdn() {
if (is_admin()) {
return;
}
/*
* Si estamos dentro de Oxygen o Breakdance,
* esta carga la controla alcastromol_tailwind_builder_iframe_cdn().
*/
if (alcastromol_is_tailwind_builder_context()) {
return;
}
if (!alcastromol_is_tailwind_developer_mode()) {
return;
}
alcastromol_tailwind_cdn_script();
}
add_action('wp_head', 'alcastromol_tailwind_front_cdn', PHP_INT_MAX);
/*
|--------------------------------------------------------------------------
| Cargar CDN en admin solo dentro de Oxygen / Breakdance
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_admin_cdn() {
/*
* Solo admin.
*/
if (!is_admin()) {
return;
}
/*
* Admin normal: no carga CDN.
*/
if (!alcastromol_is_tailwind_builder_context()) {
return;
}
/*
* Admin dentro del builder: sí carga CDN.
*/
alcastromol_tailwind_cdn_script();
}
add_action('admin_head', 'alcastromol_tailwind_admin_cdn', PHP_INT_MAX);
/*
|--------------------------------------------------------------------------
| Cargar CDN en iframe/front de Oxygen / Breakdance
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_builder_iframe_cdn() {
/*
* Esta parte aplica al iframe/front del builder,
* no al admin normal.
*/
if (is_admin()) {
return;
}
/*
* Front normal: no carga CDN en producción.
*/
if (!alcastromol_is_tailwind_builder_context()) {
return;
}
/*
* Dentro del iframe del builder: sí carga CDN.
*/
alcastromol_tailwind_cdn_script();
}
add_action('wp_head', 'alcastromol_tailwind_builder_iframe_cdn', PHP_INT_MAX);
/*
|--------------------------------------------------------------------------
| Obtener binario Standalone CLI de Tailwind
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_get_cli_path() {
$candidates = [];
if (defined('PHP_OS_FAMILY') && PHP_OS_FAMILY === 'Windows') {
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss-windows-x64.exe';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss.exe';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss-windows-x64.exe';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss.exe';
} elseif (defined('PHP_OS_FAMILY') && PHP_OS_FAMILY === 'Darwin') {
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss-macos-x64';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss-macos-arm64';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss-macos-x64';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss-macos-arm64';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss';
} else {
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss-linux-x64';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss-linux-arm64';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'bin/tailwindcss';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss-linux-x64';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss-linux-arm64';
$candidates[] = ALCASTROMOL_TAILWIND_BASE_DIR . 'tailwindcss';
}
$candidates = apply_filters('alcastromol_tailwind_cli_candidates', $candidates);
foreach ($candidates as $candidate) {
if (is_string($candidate) && file_exists($candidate) && is_file($candidate)) {
return $candidate;
}
}
return false;
}
/*
|--------------------------------------------------------------------------
| Validar si proc_open está disponible
|--------------------------------------------------------------------------
*/
function alcastromol_tailwind_can_run_processes() {
if (!function_exists('proc_open')) {
return false;
}
$disabled = ini_get('disable_functions');
if (!$disabled) {
return true;
}
$disabled_functions = array_map('trim', explode(',', $disabled));
return !in_array('proc_open', $disabled_functions, true);
}
/*
|--------------------------------------------------------------------------
| Compilar Tailwind v3 con Standalone CLI
|--------------------------------------------------------------------------
*/
function alcastromol_compile_tailwind_standalone_cli() {
if (alcastromol_get_tailwind_mode() !== 'production') {
return [
'success' => false,
'message' => 'Tailwind solo se puede compilar desde este botón cuando el modo productivo está activo.',
];
}
if (!file_exists(ALCASTROMOL_TAILWIND_INPUT_CSS)) {
return [
'success' => false,
'message' => 'No existe el archivo de entrada: ' . ALCASTROMOL_TAILWIND_INPUT_CSS,
];
}
/*
* Antes de compilar, regeneramos tailwind.config.js
* usando la configuración guardada desde el admin.
*/
$config_result = alcastromol_tailwind_generate_config_file();
if (empty($config_result['success'])) {
return [
'success' => false,
'message' => 'No se pudo generar tailwind.config.js antes de compilar. ' . ($config_result['message'] ?? ''),
];
}
if (!file_exists(ALCASTROMOL_TAILWIND_CONFIG)) {
return [
'success' => false,
'message' => 'No existe el archivo de configuración: ' . ALCASTROMOL_TAILWIND_CONFIG,
];
}
$output_dir = dirname(ALCASTROMOL_TAILWIND_OUTPUT_CSS);
if (!file_exists($output_dir)) {
wp_mkdir_p($output_dir);
}
if (!is_dir($output_dir) || !is_writable($output_dir)) {
return [
'success' => false,
'message' => 'La carpeta de salida no existe o no tiene permisos de escritura: ' . $output_dir,
];
}
$cli_path = alcastromol_tailwind_get_cli_path();
if (!$cli_path) {
return [
'success' => false,
'message' => 'No se encontró el binario Standalone CLI de Tailwind. Colócalo en functions/tailwindcss/bin/tailwindcss-linux-x64 o functions/tailwindcss/bin/tailwindcss.',
];
}
if (!is_executable($cli_path) && (!defined('PHP_OS_FAMILY') || PHP_OS_FAMILY !== 'Windows')) {
@chmod($cli_path, 0755);
}
if (!is_executable($cli_path) && (!defined('PHP_OS_FAMILY') || PHP_OS_FAMILY !== 'Windows')) {
return [
'success' => false,
'message' => 'El binario de Tailwind existe, pero no tiene permisos de ejecución: ' . $cli_path,
];
}
if (!alcastromol_tailwind_can_run_processes()) {
return [
'success' => false,
'message' => 'PHP no puede ejecutar procesos porque proc_open no está disponible o está deshabilitado en el servidor.',
];
}
$command_parts = [
$cli_path,
'-i', ALCASTROMOL_TAILWIND_INPUT_CSS,
'-o', ALCASTROMOL_TAILWIND_OUTPUT_CSS,
'-c', ALCASTROMOL_TAILWIND_CONFIG,
'--minify',
];
$command = implode(' ', array_map('escapeshellarg', $command_parts));
$descriptor_spec = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$pipes = [];
$process = proc_open(
$command,
$descriptor_spec,
$pipes,
ALCASTROMOL_TAILWIND_BASE_DIR
);
if (!is_resource($process)) {
return [
'success' => false,
'message' => 'No se pudo iniciar el proceso de compilación de Tailwind.',
];
}
fclose($pipes[0]);
$stdout = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$stderr = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$exit_code = proc_close($process);
clearstatcache(true, ALCASTROMOL_TAILWIND_OUTPUT_CSS);
if ($exit_code !== 0) {
return [
'success' => false,
'message' => 'Tailwind no pudo compilar. Código de salida: ' . $exit_code,
'stdout' => trim($stdout),
'stderr' => trim($stderr),
'command' => $command,
'cli_path' => $cli_path,
];
}
if (!file_exists(ALCASTROMOL_TAILWIND_OUTPUT_CSS)) {
return [
'success' => false,
'message' => 'Tailwind terminó sin error, pero no se generó el archivo CSS de salida.',
'stdout' => trim($stdout),
'stderr' => trim($stderr),
];
}
return [
'success' => true,
'message' => 'Tailwind v3 compilado correctamente con Standalone CLI.',
'stdout' => trim($stdout),
'stderr' => trim($stderr),
'cli_path' => $cli_path,
'output_file' => ALCASTROMOL_TAILWIND_OUTPUT_CSS,
'file_size' => size_format(filesize(ALCASTROMOL_TAILWIND_OUTPUT_CSS)),
'modified' => date_i18n('d/m/Y g:i a', filemtime(ALCASTROMOL_TAILWIND_OUTPUT_CSS)),
];
}
/*
|--------------------------------------------------------------------------
| Guardar modo desde admin
|--------------------------------------------------------------------------
*/
add_action('admin_post_alcastromol_save_tailwind_mode', function () {
if (!current_user_can('manage_options')) {
wp_die('No tienes permisos para hacer esto.');
}
check_admin_referer('alcastromol_tailwind_mode_nonce');
$mode = isset($_POST['tailwind_mode']) ? sanitize_text_field($_POST['tailwind_mode']) : 'production';
if (!in_array($mode, ['developer', 'production'], true)) {
$mode = 'production';
}
update_option(ALCASTROMOL_TAILWIND_MODE_OPTION, $mode);
$css_output = isset($_POST['tailwind_css_output']) ? sanitize_text_field($_POST['tailwind_css_output']) : 'file';
if (!in_array($css_output, ['file', 'inline'], true)) {
$css_output = 'file';
}
update_option(ALCASTROMOL_TAILWIND_CSS_OUTPUT_OPTION, $css_output);
$oxygen_enabled = !empty($_POST['oxygen_enabled']) ? '1' : '0';
if (!alcastromol_is_oxygen_installed()) {
$oxygen_enabled = '0';
}
update_option(ALCASTROMOL_OXYGEN_ENABLED_OPTION, $oxygen_enabled);
wp_redirect(
add_query_arg(
[
'page' => 'alcastromol-tailwind-mode',
'updated' => 'true',
],
admin_url('admin.php')
)
);
exit;
});
/*
|--------------------------------------------------------------------------
| Guardar configuración de Tailwind desde admin
|--------------------------------------------------------------------------
*/
add_action('admin_post_alcastromol_save_tailwind_settings', function () {
if (!current_user_can('manage_options')) {
wp_die('No tienes permisos para hacer esto.');
}
check_admin_referer('alcastromol_tailwind_settings_nonce');
$content_raw = isset($_POST['tailwind_content']) ? wp_unslash($_POST['tailwind_content']) : '';
$theme_raw = isset($_POST['tailwind_theme']) ? wp_unslash($_POST['tailwind_theme']) : '';
$content = json_decode($content_raw, true);
$theme = json_decode($theme_raw, true);
if (!is_array($content)) {
wp_redirect(
add_query_arg(
[
'page' => 'alcastromol-tailwind-mode',
'settings_error' => 'content_json',
],
admin_url('admin.php')
)
);
exit;
}
if (!is_array($theme)) {
wp_redirect(
add_query_arg(
[
'page' => 'alcastromol-tailwind-mode',
'settings_error' => 'theme_json',
],
admin_url('admin.php')
)
);
exit;
}
$settings = [
'content' => $content,
'theme' => $theme,
'plugins' => [],
];
update_option(ALCASTROMOL_TAILWIND_SETTINGS_OPTION, $settings);
$result = alcastromol_tailwind_generate_config_file();
set_transient(
'alcastromol_tailwind_config_result_' . get_current_user_id(),
$result,
120
);
wp_redirect(
add_query_arg(
[
'page' => 'alcastromol-tailwind-mode',
'settings_updated' => !empty($result['success']) ? 'true' : 'false',
],
admin_url('admin.php')
)
);
exit;
});
/*
|--------------------------------------------------------------------------
| Compilar Tailwind desde admin
|--------------------------------------------------------------------------
*/
add_action('admin_post_alcastromol_compile_tailwind_cli', function () {
if (!current_user_can('manage_options')) {
wp_die('No tienes permisos para hacer esto.');
}
check_admin_referer('alcastromol_compile_tailwind_cli_nonce');
$result = alcastromol_compile_tailwind_standalone_cli();
set_transient(
'alcastromol_tailwind_compile_result_' . get_current_user_id(),
$result,
120
);
wp_redirect(
add_query_arg(
[
'page' => 'tailwind-cache',
'compiled' => !empty($result['success']) ? 'true' : 'false',
],
admin_url('admin.php')
)
);
exit;
});
/*
|--------------------------------------------------------------------------
| Página admin
|--------------------------------------------------------------------------
*/
add_action('admin_menu', function () {
add_submenu_page(
'alcastromol-functions',
'Tailwind v3',
'Tailwind v3',
'manage_options',
'alcastromol-tailwind-mode',
'alcastromol_tailwind_mode_page'
);
}, 11);
function alcastromol_tailwind_mode_page() {
$mode = alcastromol_get_tailwind_mode();
$css_output = alcastromol_get_tailwind_css_output();
$cli_path = alcastromol_tailwind_get_cli_path();
$oxygen_installed = alcastromol_is_oxygen_installed();
$oxygen_enabled = alcastromol_is_oxygen_enabled();
$tailwind_settings = alcastromol_tailwind_get_settings();
$compile_result = get_transient('alcastromol_tailwind_compile_result_' . get_current_user_id());
if ($compile_result) {
delete_transient('alcastromol_tailwind_compile_result_' . get_current_user_id());
}
$config_result = get_transient('alcastromol_tailwind_config_result_' . get_current_user_id());
if ($config_result) {
delete_transient('alcastromol_tailwind_config_result_' . get_current_user_id());
}
?>
<div class="wrap">
<h1>Modo Tailwind</h1>
<?php if (isset($_GET['updated']) && $_GET['updated'] === 'true') : ?>
<div class="notice notice-success is-dismissible">
<p>Modo Tailwind actualizado correctamente.</p>
</div>
<?php endif; ?>
<?php if (isset($_GET['settings_error'])) : ?>
<div class="notice notice-error is-dismissible">
<p>
Error: revisa que el JSON de configuración sea válido.
<?php if ($_GET['settings_error'] === 'content_json') : ?>
El problema está en <code>Content</code>.
<?php elseif ($_GET['settings_error'] === 'theme_json') : ?>
El problema está en <code>Theme</code>.
<?php endif; ?>
</p>
</div>
<?php endif; ?>
<?php if (is_array($config_result)) : ?>
<?php if (!empty($config_result['success'])) : ?>
<div class="notice notice-success is-dismissible">
<p><strong><?php echo esc_html($config_result['message']); ?></strong></p>
<?php if (!empty($config_result['file'])) : ?>
<p>
Archivo:
<code><?php echo esc_html($config_result['file']); ?></code>
</p>
<?php endif; ?>
<?php if (!empty($config_result['size'])) : ?>
<p>
Tamaño:
<code><?php echo esc_html($config_result['size']); ?></code>
</p>
<?php endif; ?>
</div>
<?php else : ?>
<div class="notice notice-error is-dismissible">
<p><strong>Error al generar tailwind.config.js.</strong></p>
<p><?php echo esc_html($config_result['message'] ?? 'Error desconocido.'); ?></p>
</div>
<?php endif; ?>
<?php endif; ?>
<?php if (is_array($compile_result)) : ?>
<?php if (!empty($compile_result['success'])) : ?>
<div class="notice notice-success is-dismissible">
<p><strong><?php echo esc_html($compile_result['message']); ?></strong></p>
<?php if (!empty($compile_result['file_size']) || !empty($compile_result['modified'])) : ?>
<p>
<?php if (!empty($compile_result['file_size'])) : ?>
Tamaño: <code><?php echo esc_html($compile_result['file_size']); ?></code>
<?php endif; ?>
<?php if (!empty($compile_result['modified'])) : ?>
&nbsp; Última modificación: <code><?php echo esc_html($compile_result['modified']); ?></code>
<?php endif; ?>
</p>
<?php endif; ?>
<?php if (!empty($compile_result['stdout'])) : ?>
<pre style="white-space:pre-wrap;"><?php echo esc_html($compile_result['stdout']); ?></pre>
<?php endif; ?>
</div>
<?php else : ?>
<div class="notice notice-error is-dismissible">
<p><strong>Error al compilar Tailwind.</strong></p>
<p><?php echo esc_html($compile_result['message'] ?? 'Error desconocido.'); ?></p>
<?php if (!empty($compile_result['stderr'])) : ?>
<p><strong>Error:</strong></p>
<pre style="white-space:pre-wrap;"><?php echo esc_html($compile_result['stderr']); ?></pre>
<?php endif; ?>
<?php if (!empty($compile_result['stdout'])) : ?>
<p><strong>Salida:</strong></p>
<pre style="white-space:pre-wrap;"><?php echo esc_html($compile_result['stdout']); ?></pre>
<?php endif; ?>
</div>
<?php endif; ?>
<?php endif; ?>
<?php if (!$oxygen_enabled) : ?>
<div class="notice notice-info">
<p>
<strong>Oxygen desactivado.</strong>
Tailwind v3 funciona de forma independiente con el tema de WordPress:
CDN en modo developer y CSS compilado en modo productivo.
Al compilar se escanean también los archivos PHP/HTML/JS del tema activo.
</p>
</div>
<?php endif; ?>
<p>
Selecciona cómo quieres cargar Tailwind en el sitio.
</p>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<?php wp_nonce_field('alcastromol_tailwind_mode_nonce'); ?>
<input type="hidden" name="action" value="alcastromol_save_tailwind_mode">
<table class="form-table" role="presentation">
<tr>
<th scope="row">Integración Oxygen</th>
<td>
<fieldset>
<label>
<input
type="checkbox"
name="oxygen_enabled"
value="1"
<?php checked($oxygen_enabled); ?>
<?php disabled(!$oxygen_installed); ?>
>
<strong>Usar Oxygen Builder</strong>
</label>
<p class="description" style="margin-top:8px;">
<?php if (!$oxygen_installed) : ?>
Oxygen no está instalado. Tailwind funciona sin él. Si lo instalas, podrás activar esta casilla.
<?php else : ?>
Si lo desactivas, el plugin no depende de Oxygen y Tailwind v3 sigue funcionando en el tema personalizado.
<?php endif; ?>
</p>
</fieldset>
</td>
</tr>
<tr>
<th scope="row">Modo actual</th>
<td>
<fieldset>
<label style="display:block; margin-bottom:14px;">
<input
type="radio"
name="tailwind_mode"
value="developer"
<?php checked($mode, 'developer'); ?>
>
<strong>Modo de desarrollo Developer</strong>
<br>
<span class="description">
<?php if ($oxygen_enabled) : ?>
Carga el CDN de Tailwind en el front end normal y dentro de Oxygen/Breakdance.
<?php else : ?>
Carga el CDN de Tailwind en el front end del tema.
<?php endif; ?>
</span>
</label>
<label style="display:block; margin-bottom:14px;">
<input
type="radio"
name="tailwind_mode"
value="production"
<?php checked($mode, 'production'); ?>
>
<strong>Modo productivo</strong>
<br>
<span class="description">
<?php if ($oxygen_enabled) : ?>
Carga el CSS compilado en front end normal y el CDN solo dentro de Oxygen/Breakdance.
<?php else : ?>
Carga el CSS compilado de Tailwind en el front end del tema.
<?php endif; ?>
</span>
</label>
</fieldset>
</td>
</tr>
<tr>
<th scope="row">Salida del CSS</th>
<td>
<fieldset>
<label style="display:block; margin-bottom:14px;">
<input
type="radio"
name="tailwind_css_output"
value="file"
<?php checked($css_output, 'file'); ?>
>
<strong>Archivo <code>.css</code></strong>
<br>
<span class="description">
Carga <code>styles-tailwind.css</code> con <code>&lt;link rel="stylesheet"&gt;</code>.
El navegador puede cachear el archivo y reutilizarlo en las siguientes páginas.
</span>
</label>
<label style="display:block; margin-bottom:14px;">
<input
type="radio"
name="tailwind_css_output"
value="inline"
<?php checked($css_output, 'inline'); ?>
>
<strong>CSS en el header (<code>&lt;style&gt;</code>)</strong>
<br>
<span class="description">
Inserta el CSS compilado dentro de <code>&lt;head&gt;</code>.
Evita una petición HTTP extra y puede mejorar el primer pintado.
</span>
</label>
<p class="description">
Esta opción solo aplica en <strong>Modo productivo</strong>. En developer se sigue usando el CDN.
</p>
</fieldset>
</td>
</tr>
</table>
<?php submit_button('Guardar cambios'); ?>
</form>
<hr>
<h2>Configuración de Tailwind</h2>
<p>
Edita aquí la configuración principal de Tailwind. Desde esta configuración se genera automáticamente:
</p>
<ul style="list-style:disc; padding-left:20px;">
<li>El script <code>window.tailwind.config</code> usado por el CDN.</li>
<li>El archivo físico <code>tailwind.config.js</code> usado para compilar en producción.</li>
</ul>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<?php wp_nonce_field('alcastromol_tailwind_settings_nonce'); ?>
<input type="hidden" name="action" value="alcastromol_save_tailwind_settings">
<table class="form-table" role="presentation">
<tr>
<th scope="row">
Content
</th>
<td>
<textarea
name="tailwind_content"
rows="6"
style="width:100%; max-width:900px; font-family:monospace;"
><?php echo esc_textarea(wp_json_encode($tailwind_settings['content'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); ?></textarea>
<p class="description">
Rutas que Tailwind escanea para detectar clases.
Ejemplo: <code>./cache/*.{php,html,js}</code>
<?php if (!$oxygen_enabled) : ?>
<br>Con Oxygen desactivado, al compilar también se agregan los archivos del tema activo.
<?php endif; ?>
</p>
</td>
</tr>
<tr>
<th scope="row">
Theme
</th>
<td>
<textarea
name="tailwind_theme"
rows="28"
style="width:100%; max-width:900px; font-family:monospace;"
><?php echo esc_textarea(wp_json_encode($tailwind_settings['theme'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); ?></textarea>
<p class="description">
Aquí defines <code>screens</code>, <code>container</code>, <code>extend.colors</code> y demás opciones del tema.
</p>
</td>
</tr>
</table>
<?php submit_button('Guardar configuración y generar tailwind.config.js'); ?>
</form>
<hr>
<h2>Estado actual</h2>
<?php if ($mode === 'developer') : ?>
<p>
<strong>Modo activo:</strong> Developer
</p>
<table class="widefat striped" style="max-width:700px;">
<thead>
<tr>
<th>Área</th>
<th>Archivo cargado</th>
</tr>
</thead>
<tbody>
<tr>
<td>Admin normal</td>
<td>No carga Tailwind CDN</td>
</tr>
<?php if ($oxygen_enabled) : ?>
<tr>
<td>Constructor Oxygen 6</td>
<td>CDN Tailwind con configuración generada desde admin</td>
</tr>
<tr>
<td>Constructor Breakdance</td>
<td>CDN Tailwind con configuración generada desde admin</td>
</tr>
<?php endif; ?>
<tr>
<td>Front end <?php echo $oxygen_enabled ? 'normal' : 'del tema'; ?></td>
<td>CDN Tailwind con configuración generada desde admin</td>
</tr>
<tr>
<td>CSS productivo</td>
<td>No se carga en front end normal</td>
</tr>
</tbody>
</table>
<div class="notice notice-info inline" style="max-width:700px; margin-top:16px;">
<p>
Para compilar Tailwind con Standalone CLI, cambia primero a <strong>Modo productivo</strong>.
</p>
</div>
<?php else : ?>
<p>
<strong>Modo activo:</strong> Productivo
</p>
<table class="widefat striped" style="max-width:700px;">
<thead>
<tr>
<th>Área</th>
<th>Archivo cargado</th>
</tr>
</thead>
<tbody>
<tr>
<td>Admin normal</td>
<td>No carga Tailwind CDN</td>
</tr>
<?php if ($oxygen_enabled) : ?>
<tr>
<td>Constructor Oxygen 6</td>
<td>CDN Tailwind con configuración generada desde admin</td>
</tr>
<tr>
<td>Constructor Breakdance</td>
<td>CDN Tailwind con configuración generada desde admin</td>
</tr>
<?php endif; ?>
<tr>
<td>Front end <?php echo $oxygen_enabled ? 'normal' : 'del tema'; ?></td>
<td>
<?php if ($css_output === 'inline') : ?>
CSS compilado en el header: <code>&lt;style id="alcastromol-tailwind-css"&gt;</code>
<?php else : ?>
CSS compilado: <code>styles-tailwind.css</code>
<?php endif; ?>
</td>
</tr>
<tr>
<td>CDN en front end normal</td>
<td>No se carga</td>
</tr>
</tbody>
</table>
<?php endif; ?>
<hr>
<h2>Notas</h2>
<p>
El CDN se imprime con prioridad <code>PHP_INT_MAX</code> en <code>wp_head</code> y <code>admin_head</code>.
Esto evita usar buffer, que puede romper Oxygen, Breakdance o la carga normal de WordPress.
</p>
<?php if ($oxygen_enabled) : ?>
<p>
Parámetros detectados para Oxygen:
<code>ct_builder</code>,
<code>ct_inner</code>,
<code>oxygen_iframe</code>,
<code>oxygen_builder</code>,
<code>ct_sign_sha256</code>,
<code>ct_template</code>.
</p>
<p>
Parámetros detectados para Breakdance:
<code>breakdance</code>,
<code>breakdance_builder</code>,
<code>breakdance_iframe</code>,
<code>breakdance_preview</code>,
<code>breakdance_open</code>,
<code>breakdance_canvas</code>,
<code>breakdance_editor</code>.
</p>
<p>
Dentro de Oxygen o Breakdance, tanto en modo developer como en modo productivo, se carga el CDN para poder visualizar clases nuevas dentro del constructor.
</p>
<?php else : ?>
<p>
Con Oxygen desactivado, Tailwind no inyecta scripts del constructor y usa el tema de WordPress.
</p>
<?php endif; ?>
<p>
En modo productivo, el front end normal carga el CSS compilado de una de estas formas:
</p>
<ul style="list-style:disc; padding-left:20px;">
<li><strong>Archivo .css:</strong> <code>tailwindcss/css-production/styles-tailwind.css</code> con <code>&lt;link&gt;</code>.</li>
<li><strong>Header:</strong> el mismo CSS dentro de <code>&lt;style id="alcastromol-tailwind-css"&gt;</code>, justo antes de <code>&lt;/head&gt;</code>.</li>
</ul>
<p>
El archivo <code>tailwind.config.js</code> ya no se debe editar manualmente.
Ahora se genera desde la configuración guardada en esta pantalla.
</p>
</div>
<?php
}