Files

1875 lines
48 KiB
PHP

<?php
if (!defined('ABSPATH')) exit;
define('ALCASTROMOL_TAILWIND_CACHE', ALCASTROMOL_PLUGIN_PATH . 'functions/tailwindcss/cache/');
define('ALCASTROMOL_TAILWIND_CACHE_OPTIONS', 'alcastromol_tailwind_cache_options');
/*
|--------------------------------------------------------------------------
| Crear carpeta cache
|--------------------------------------------------------------------------
*/
add_action('init', function () {
if (!file_exists(ALCASTROMOL_TAILWIND_CACHE)) {
wp_mkdir_p(ALCASTROMOL_TAILWIND_CACHE);
}
});
/*
|--------------------------------------------------------------------------
| Opciones por defecto
|--------------------------------------------------------------------------
*/
function alcastromol_get_default_cache_options() {
return [
'home' => 1,
'post_types' => [],
'taxonomies' => [],
'authors' => 0,
'oxygen_templates' => alcastromol_is_oxygen_enabled() ? 1 : 0,
];
}
/*
|--------------------------------------------------------------------------
| Obtener opciones guardadas
|--------------------------------------------------------------------------
*/
function alcastromol_get_cache_options() {
$saved = get_option(ALCASTROMOL_TAILWIND_CACHE_OPTIONS, []);
if (!is_array($saved)) {
$saved = [];
}
return wp_parse_args($saved, alcastromol_get_default_cache_options());
}
/*
|--------------------------------------------------------------------------
| Guardar opciones
|--------------------------------------------------------------------------
*/
function alcastromol_save_cache_options($options) {
$clean = alcastromol_get_default_cache_options();
$clean['home'] = !empty($options['home']) ? 1 : 0;
$clean['post_types'] = [];
if (!empty($options['post_types']) && is_array($options['post_types'])) {
foreach ($options['post_types'] as $post_type) {
$clean['post_types'][] = sanitize_key($post_type);
}
}
$clean['taxonomies'] = [];
if (!empty($options['taxonomies']) && is_array($options['taxonomies'])) {
foreach ($options['taxonomies'] as $taxonomy) {
$clean['taxonomies'][] = sanitize_key($taxonomy);
}
}
$clean['authors'] = !empty($options['authors']) ? 1 : 0;
$clean['oxygen_templates'] = (alcastromol_is_oxygen_enabled() && !empty($options['oxygen_templates'])) ? 1 : 0;
update_option(ALCASTROMOL_TAILWIND_CACHE_OPTIONS, $clean);
return $clean;
}
/*
|--------------------------------------------------------------------------
| Detectar post types cacheables
|--------------------------------------------------------------------------
*/
function alcastromol_detect_cacheable_post_types() {
$post_types = get_post_types([
'public' => true,
], 'objects');
$exclude = [
'attachment',
];
$items = [];
foreach ($post_types as $post_type => $object) {
if (in_array($post_type, $exclude, true)) {
continue;
}
$items[$post_type] = [
'name' => $post_type,
'label' => $object->labels->name ?? $post_type,
];
}
if (post_type_exists('product') && !isset($items['product'])) {
$items['product'] = [
'name' => 'product',
'label' => 'Productos WooCommerce',
];
}
return $items;
}
/*
|--------------------------------------------------------------------------
| Detectar taxonomías cacheables
|--------------------------------------------------------------------------
*/
function alcastromol_detect_cacheable_taxonomies() {
$taxonomies = get_taxonomies([
'public' => true,
], 'objects');
$items = [];
foreach ($taxonomies as $taxonomy => $object) {
$items[$taxonomy] = [
'name' => $taxonomy,
'label' => $object->labels->name ?? $taxonomy,
];
}
return $items;
}
/*
|--------------------------------------------------------------------------
| Obtener HTML final renderizado
|--------------------------------------------------------------------------
*/
function alcastromol_fetch_html($url) {
$response = wp_remote_get($url, [
'timeout' => 20,
'sslverify' => false,
'headers' => [
'User-Agent' => 'Alcastromol Tailwind Cache Generator',
],
]);
if (is_wp_error($response)) {
return false;
}
$code = wp_remote_retrieve_response_code($response);
if ($code < 200 || $code >= 400) {
return false;
}
$html = wp_remote_retrieve_body($response);
if (!$html) {
return false;
}
return $html;
}
/*
|--------------------------------------------------------------------------
| Limpiar HTML
|--------------------------------------------------------------------------
*/
function alcastromol_clean_html($html) {
$html = preg_replace('/<!--(.|\s)*?-->/', '', $html);
return $html;
}
/*
|--------------------------------------------------------------------------
| Guardar cache
|--------------------------------------------------------------------------
*/
function alcastromol_save_cache($slug, $html) {
if (!file_exists(ALCASTROMOL_TAILWIND_CACHE)) {
wp_mkdir_p(ALCASTROMOL_TAILWIND_CACHE);
}
$file = ALCASTROMOL_TAILWIND_CACHE . sanitize_file_name($slug) . '.html';
file_put_contents($file, $html);
}
/*
|--------------------------------------------------------------------------
| Eliminar archivo individual
|--------------------------------------------------------------------------
*/
function alcastromol_delete_cache_file($slug) {
$file = ALCASTROMOL_TAILWIND_CACHE . sanitize_file_name($slug) . '.html';
if (file_exists($file)) {
unlink($file);
}
}
/*
|--------------------------------------------------------------------------
| Eliminar todo el cache
|--------------------------------------------------------------------------
*/
function alcastromol_delete_all_cache() {
if (!file_exists(ALCASTROMOL_TAILWIND_CACHE)) {
return 0;
}
$files = glob(ALCASTROMOL_TAILWIND_CACHE . '*.html');
if (!$files) {
return 0;
}
$deleted = 0;
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
$deleted++;
}
}
return $deleted;
}
/*
|--------------------------------------------------------------------------
| Patrones, conteos y acciones por tipo de contenido
|--------------------------------------------------------------------------
*/
function alcastromol_get_cache_patterns_by_target($target_type, $target_name = '') {
$target_type = sanitize_key($target_type);
$target_name = sanitize_key($target_name);
switch ($target_type) {
case 'home':
return ['home.html'];
case 'post_type':
if (!$target_name) return [];
return [$target_name . '-*.html'];
case 'taxonomy':
if (!$target_name) return [];
return ['taxonomy-' . $target_name . '-*.html'];
case 'oxygen_templates':
return ['oxygen-template-*.html'];
case 'authors':
return ['author-*.html'];
}
return [];
}
function alcastromol_get_cache_files_by_target($target_type, $target_name = '') {
if (!file_exists(ALCASTROMOL_TAILWIND_CACHE)) {
return [];
}
$patterns = alcastromol_get_cache_patterns_by_target($target_type, $target_name);
if (empty($patterns)) {
return [];
}
$files = [];
foreach ($patterns as $pattern) {
$found = glob(ALCASTROMOL_TAILWIND_CACHE . $pattern);
if (!empty($found)) {
$files = array_merge($files, $found);
}
}
$files = array_filter(array_unique($files), 'is_file');
return array_values($files);
}
function alcastromol_count_cache_files_by_target($target_type, $target_name = '') {
return count(alcastromol_get_cache_files_by_target($target_type, $target_name));
}
function alcastromol_delete_cache_by_target($target_type, $target_name = '') {
$files = alcastromol_get_cache_files_by_target($target_type, $target_name);
if (empty($files)) {
return 0;
}
$deleted = 0;
foreach ($files as $file) {
if (is_file($file) && unlink($file)) {
$deleted++;
}
}
return $deleted;
}
function alcastromol_get_urls_by_cache_target($target_type, $target_name = '') {
$target_type = sanitize_key($target_type);
$target_name = sanitize_key($target_name);
$items = [];
if ($target_type === 'home') {
$items[] = [
'url' => home_url('/'),
'slug' => 'home',
'type' => 'home',
];
return $items;
}
if ($target_type === 'post_type') {
if (!$target_name || !post_type_exists($target_name)) {
return [];
}
$post_ids = get_posts([
'post_type' => $target_name,
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids',
'no_found_rows' => true,
'ignore_sticky_posts' => true,
'suppress_filters' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
]);
foreach ($post_ids as $post_id) {
$post = get_post($post_id);
if (!$post) continue;
$permalink = get_permalink($post_id);
if (!$permalink) continue;
$items[] = [
'url' => $permalink,
'slug' => $post->post_type . '-' . $post->ID . '-' . $post->post_name,
'type' => $post->post_type,
];
}
return $items;
}
if ($target_type === 'taxonomy') {
if (!$target_name || !taxonomy_exists($target_name)) {
return [];
}
$terms = get_terms([
'taxonomy' => $target_name,
'hide_empty' => false,
]);
if (is_wp_error($terms) || empty($terms)) {
return [];
}
foreach ($terms as $term) {
$term_link = get_term_link($term);
if (is_wp_error($term_link)) {
continue;
}
$items[] = [
'url' => $term_link,
'slug' => 'taxonomy-' . $target_name . '-' . $term->term_id . '-' . $term->slug,
'type' => 'taxonomy_' . $target_name,
];
}
return $items;
}
if ($target_type === 'authors') {
$authors = get_users([
'who' => 'authors',
]);
foreach ($authors as $author) {
$items[] = [
'url' => get_author_posts_url($author->ID),
'slug' => 'author-' . $author->ID . '-' . $author->user_nicename,
'type' => 'author',
];
}
return $items;
}
return $items;
}
function alcastromol_generate_cache_by_target($target_type, $target_name = '') {
$target_type = sanitize_key($target_type);
$target_name = sanitize_key($target_name);
$generated = 0;
$failed = 0;
$failed_urls = [];
$total = 0;
if ($target_type === 'oxygen_templates') {
if (!alcastromol_is_oxygen_enabled()) {
return [
'total' => 0,
'generated' => 0,
'failed' => 0,
'failed_urls' => [],
];
}
$oxygen_items = alcastromol_get_oxygen_templates_cache_items();
$total = count($oxygen_items);
foreach ($oxygen_items as $item) {
if (empty($item['slug']) || empty($item['html'])) {
$failed++;
continue;
}
$html = alcastromol_clean_html($item['html']);
alcastromol_save_cache($item['slug'], $html);
$generated++;
}
return [
'total' => $total,
'generated' => $generated,
'failed' => $failed,
'failed_urls' => $failed_urls,
'count' => alcastromol_count_cache_files_by_target($target_type, $target_name),
];
}
$items = alcastromol_get_urls_by_cache_target($target_type, $target_name);
$total = count($items);
foreach ($items as $item) {
if (empty($item['url']) || empty($item['slug'])) {
$failed++;
continue;
}
$result = alcastromol_cache_url($item['url'], $item['slug']);
if ($result) {
$generated++;
} else {
$failed++;
$failed_urls[] = $item['url'];
}
}
return [
'total' => $total,
'generated' => $generated,
'failed' => $failed,
'failed_urls' => $failed_urls,
'count' => alcastromol_count_cache_files_by_target($target_type, $target_name),
];
}
function alcastromol_render_cache_action_row($args) {
$target_type = sanitize_key($args['target_type'] ?? '');
$target_name = sanitize_key($args['target_name'] ?? '');
$label = $args['label'] ?? '';
$code = $args['code'] ?? '';
$input_name = $args['input_name'] ?? '';
$input_value = $args['input_value'] ?? '';
$checked = !empty($args['checked']);
$count = alcastromol_count_cache_files_by_target($target_type, $target_name);
?>
<div class="alcastromol-cache-row">
<label class="alcastromol-cache-label">
<?php if ($input_name) : ?>
<input
type="checkbox"
name="<?php echo esc_attr($input_name); ?>"
value="<?php echo esc_attr($input_value); ?>"
<?php checked($checked); ?>
>
<?php endif; ?>
<span><?php echo esc_html($label); ?></span>
<?php if ($code) : ?>
<code><?php echo esc_html($code); ?></code>
<?php endif; ?>
</label>
<span class="alcastromol-cache-count" data-cache-count="<?php echo esc_attr($target_type); ?>|<?php echo esc_attr($target_name); ?>">
<?php echo esc_html($count); ?> archivos
</span>
<button
type="button"
class="button alcastromol-generate-cache-target"
data-target-type="<?php echo esc_attr($target_type); ?>"
data-target-name="<?php echo esc_attr($target_name); ?>"
>
Generar
</button>
<button
type="button"
class="button alcastromol-delete-cache-target"
data-target-type="<?php echo esc_attr($target_type); ?>"
data-target-name="<?php echo esc_attr($target_name); ?>"
style="border-color:#b32d2e; color:#b32d2e;"
>
Borrar
</button>
</div>
<?php
}
/*
|--------------------------------------------------------------------------
| Generar cache de URL pública
|--------------------------------------------------------------------------
*/
function alcastromol_cache_url($url, $slug) {
if (function_exists('alcastromol_is_module_active') && !alcastromol_is_module_active('cache')) {
return false;
}
$html = alcastromol_fetch_html($url);
if (!$html) {
return false;
}
$html = alcastromol_clean_html($html);
alcastromol_save_cache($slug, $html);
return true;
}
/*
|--------------------------------------------------------------------------
| Generar slug de cache para post
|--------------------------------------------------------------------------
*/
function alcastromol_get_post_cache_slug($post_id) {
$post = get_post($post_id);
if (!$post) {
return false;
}
return $post->post_type . '-' . $post->ID . '-' . $post->post_name;
}
/*
|--------------------------------------------------------------------------
| Cache individual al guardar Gutenberg / post / page / CPT / product
|--------------------------------------------------------------------------
*/
function alcastromol_cache_post($post_id) {
if (wp_is_post_revision($post_id)) return;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
$post = get_post($post_id);
if (!$post) return;
if ($post->post_status !== 'publish') return;
/*
| Si es template Oxygen, lo cacheamos con la función especial.
*/
if ($post->post_type === 'ct_template') {
if (alcastromol_is_oxygen_enabled()) {
alcastromol_cache_oxygen_template($post_id);
}
return;
}
$options = alcastromol_get_cache_options();
if (empty($options['post_types']) || !in_array($post->post_type, $options['post_types'], true)) {
return;
}
$url = get_permalink($post_id);
if (!$url) return;
$slug = alcastromol_get_post_cache_slug($post_id);
if (!$slug) return;
alcastromol_cache_url($url, $slug);
}
add_action('save_post', 'alcastromol_cache_post', 30);
add_action('save_post_product', 'alcastromol_cache_post', 30);
add_action('save_post_ct_template', 'alcastromol_cache_post', 30);
/*
|--------------------------------------------------------------------------
| Obtener HTML/metas de un template Oxygen
|--------------------------------------------------------------------------
*/
function alcastromol_get_oxygen_template_html($template_id) {
$post = get_post($template_id);
if (!$post || $post->post_type !== 'ct_template') {
return false;
}
$html_parts = [];
if (!empty($post->post_content)) {
$html_parts[] = $post->post_content;
}
$possible_meta_keys = [
'ct_builder_shortcodes',
'ct_builder_json',
'ct_template_type',
'ct_template_order',
'ct_use_template',
'ct_parent_template',
'ct_inner_content',
];
foreach ($possible_meta_keys as $meta_key) {
$meta_value = get_post_meta($template_id, $meta_key, true);
if (!empty($meta_value)) {
if (is_array($meta_value) || is_object($meta_value)) {
$meta_value = wp_json_encode($meta_value);
}
if (is_string($meta_value)) {
$html_parts[] = $meta_value;
}
}
}
/*
| Extra: tomar todos los metas del template.
| Oxygen puede guardar clases y estructura en distintos campos.
*/
$all_meta = get_post_meta($template_id);
if (!empty($all_meta) && is_array($all_meta)) {
foreach ($all_meta as $meta_key => $meta_values) {
if (empty($meta_values)) {
continue;
}
foreach ($meta_values as $meta_value) {
if (empty($meta_value)) {
continue;
}
if (is_array($meta_value) || is_object($meta_value)) {
$meta_value = wp_json_encode($meta_value);
}
if (is_string($meta_value)) {
$html_parts[] = $meta_value;
}
}
}
}
$html = implode("\n", array_filter($html_parts));
if (empty($html)) {
return false;
}
return $html;
}
/*
|--------------------------------------------------------------------------
| Cache individual de template Oxygen
|--------------------------------------------------------------------------
*/
function alcastromol_cache_oxygen_template($template_id) {
if (!alcastromol_is_oxygen_enabled()) {
return false;
}
$options = alcastromol_get_cache_options();
if (empty($options['oxygen_templates'])) {
return false;
}
$post = get_post($template_id);
if (!$post || $post->post_type !== 'ct_template') {
return false;
}
if (!in_array($post->post_status, ['publish', 'draft'], true)) {
return false;
}
$html = alcastromol_get_oxygen_template_html($template_id);
if (!$html) {
return false;
}
$slug = 'oxygen-template-' . $template_id . '-' . $post->post_name;
$html = alcastromol_clean_html($html);
alcastromol_save_cache($slug, $html);
return true;
}
/*
|--------------------------------------------------------------------------
| Obtener templates Oxygen para cache masivo
|--------------------------------------------------------------------------
*/
function alcastromol_get_oxygen_templates_cache_items() {
$items = [];
if (!alcastromol_is_oxygen_enabled()) {
return $items;
}
if (!post_type_exists('ct_template')) {
return $items;
}
$template_ids = get_posts([
'post_type' => 'ct_template',
'post_status' => ['publish', 'draft'],
'posts_per_page' => -1,
'fields' => 'ids',
'no_found_rows' => true,
'ignore_sticky_posts' => true,
'suppress_filters' => false,
'update_post_meta_cache' => true,
'update_post_term_cache' => false,
]);
foreach ($template_ids as $template_id) {
$post = get_post($template_id);
if (!$post) {
continue;
}
$html = alcastromol_get_oxygen_template_html($template_id);
if (!$html) {
continue;
}
$items[] = [
'slug' => 'oxygen-template-' . $template_id . '-' . $post->post_name,
'html' => $html,
];
}
return $items;
}
/*
|--------------------------------------------------------------------------
| Obtener todas las URLs públicas seleccionadas
|--------------------------------------------------------------------------
*/
function alcastromol_get_all_urls() {
$options = alcastromol_get_cache_options();
$urls = [];
/*
|--------------------------------------------------------------------------
| Home
|--------------------------------------------------------------------------
*/
if (!empty($options['home'])) {
$urls[] = [
'url' => home_url('/'),
'slug' => 'home',
'type' => 'home',
];
}
/*
|--------------------------------------------------------------------------
| Post types seleccionados
|--------------------------------------------------------------------------
*/
$selected_post_types = [];
if (!empty($options['post_types']) && is_array($options['post_types'])) {
$selected_post_types = $options['post_types'];
}
$selected_post_types = array_filter($selected_post_types, function ($post_type) {
return post_type_exists($post_type);
});
if (!empty($selected_post_types)) {
$post_ids = get_posts([
'post_type' => $selected_post_types,
'post_status' => 'publish',
'posts_per_page' => -1,
'fields' => 'ids',
'no_found_rows' => true,
'ignore_sticky_posts' => true,
'suppress_filters' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
]);
foreach ($post_ids as $post_id) {
$post = get_post($post_id);
if (!$post) continue;
$permalink = get_permalink($post_id);
if (!$permalink) continue;
$urls[] = [
'url' => $permalink,
'slug' => $post->post_type . '-' . $post->ID . '-' . $post->post_name,
'type' => $post->post_type,
];
}
}
/*
|--------------------------------------------------------------------------
| Taxonomías seleccionadas
|--------------------------------------------------------------------------
*/
$selected_taxonomies = [];
if (!empty($options['taxonomies']) && is_array($options['taxonomies'])) {
$selected_taxonomies = $options['taxonomies'];
}
$selected_taxonomies = array_filter($selected_taxonomies, function ($taxonomy) {
return taxonomy_exists($taxonomy);
});
if (!empty($selected_taxonomies)) {
foreach ($selected_taxonomies as $tax) {
$terms = get_terms([
'taxonomy' => $tax,
'hide_empty' => false,
]);
if (is_wp_error($terms) || empty($terms)) {
continue;
}
foreach ($terms as $term) {
$term_link = get_term_link($term);
if (is_wp_error($term_link)) {
continue;
}
$urls[] = [
'url' => $term_link,
'slug' => 'taxonomy-' . $tax . '-' . $term->term_id . '-' . $term->slug,
'type' => 'taxonomy_' . $tax,
];
}
}
}
/*
|--------------------------------------------------------------------------
| Autores
|--------------------------------------------------------------------------
*/
if (!empty($options['authors'])) {
$authors = get_users([
'who' => 'authors',
]);
foreach ($authors as $author) {
$urls[] = [
'url' => get_author_posts_url($author->ID),
'slug' => 'author-' . $author->ID . '-' . $author->user_nicename,
'type' => 'author',
];
}
}
/*
|--------------------------------------------------------------------------
| Eliminar URLs duplicadas
|--------------------------------------------------------------------------
*/
$unique_urls = [];
foreach ($urls as $item) {
if (empty($item['url']) || empty($item['slug'])) {
continue;
}
$unique_urls[$item['url']] = $item;
}
return array_values($unique_urls);
}
/*
|--------------------------------------------------------------------------
| Generar cache completa
|--------------------------------------------------------------------------
*/
function alcastromol_generate_full_cache() {
$options = alcastromol_get_cache_options();
$urls = alcastromol_get_all_urls();
$generated = 0;
$failed = 0;
$products = 0;
$oxygen_templates = 0;
$failed_urls = [];
/*
|--------------------------------------------------------------------------
| Cache de URLs públicas
|--------------------------------------------------------------------------
*/
foreach ($urls as $item) {
if (!empty($item['type']) && $item['type'] === 'product') {
$products++;
}
$result = alcastromol_cache_url($item['url'], $item['slug']);
if ($result) {
$generated++;
} else {
$failed++;
$failed_urls[] = $item['url'];
}
}
/*
|--------------------------------------------------------------------------
| Cache de templates Oxygen
|--------------------------------------------------------------------------
*/
if (alcastromol_is_oxygen_enabled() && !empty($options['oxygen_templates'])) {
$oxygen_items = alcastromol_get_oxygen_templates_cache_items();
foreach ($oxygen_items as $item) {
if (empty($item['slug']) || empty($item['html'])) {
continue;
}
$html = alcastromol_clean_html($item['html']);
alcastromol_save_cache($item['slug'], $html);
$oxygen_templates++;
$generated++;
}
}
return [
'total' => count($urls) + $oxygen_templates,
'products' => $products,
'oxygen_templates' => $oxygen_templates,
'generated' => $generated,
'failed' => $failed,
'failed_urls' => $failed_urls,
];
}
/*
|--------------------------------------------------------------------------
| AJAX guardar opciones
|--------------------------------------------------------------------------
*/
add_action('wp_ajax_alcastromol_save_tailwind_cache_options', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error('No tienes permisos para guardar opciones.');
}
check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
$raw_options = $_POST['options'] ?? [];
if (!is_array($raw_options)) {
$raw_options = [];
}
$options = alcastromol_save_cache_options($raw_options);
wp_send_json_success([
'message' => 'Opciones guardadas',
'options' => $options,
]);
});
/*
|--------------------------------------------------------------------------
| AJAX generar cache
|--------------------------------------------------------------------------
*/
add_action('wp_ajax_alcastromol_generate_tailwind_cache', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error('No tienes permisos para generar el cache.');
}
check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
$result = alcastromol_generate_full_cache();
wp_send_json_success([
'message' => 'Cache generada',
'total' => $result['total'],
'products' => $result['products'],
'oxygen_templates' => $result['oxygen_templates'],
'generated' => $result['generated'],
'failed' => $result['failed'],
'failed_urls' => $result['failed_urls'],
]);
});
/*
|--------------------------------------------------------------------------
| AJAX eliminar cache
|--------------------------------------------------------------------------
*/
add_action('wp_ajax_alcastromol_delete_tailwind_cache', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error('No tienes permisos para eliminar el cache.');
}
check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
$deleted = alcastromol_delete_all_cache();
wp_send_json_success([
'message' => 'Cache eliminado',
'deleted' => $deleted,
]);
});
/*
|--------------------------------------------------------------------------
| AJAX generar cache por tipo de contenido
|--------------------------------------------------------------------------
*/
add_action('wp_ajax_alcastromol_generate_tailwind_cache_target', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error('No tienes permisos para generar este cache.');
}
check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
$target_type = sanitize_key($_POST['target_type'] ?? '');
$target_name = sanitize_key($_POST['target_name'] ?? '');
$allowed = ['home', 'post_type', 'taxonomy', 'oxygen_templates', 'authors'];
if (!in_array($target_type, $allowed, true)) {
wp_send_json_error('Tipo de cache inválido.');
}
$result = alcastromol_generate_cache_by_target($target_type, $target_name);
wp_send_json_success([
'message' => 'Cache generado',
'target_type' => $target_type,
'target_name' => $target_name,
'total' => $result['total'],
'generated' => $result['generated'],
'failed' => $result['failed'],
'failed_urls' => $result['failed_urls'],
'count' => $result['count'],
]);
});
/*
|--------------------------------------------------------------------------
| POST administrativo para generar cache por tipo de contenido
|--------------------------------------------------------------------------
*/
add_action('admin_post_alcastromol_generate_tailwind_cache_target_post', function () {
if (!current_user_can('manage_options')) {
wp_die('No tienes permisos para generar este cache.');
}
check_admin_referer('alcastromol_tailwind_cache_nonce', 'nonce');
$target_type = sanitize_key($_POST['target_type'] ?? '');
$target_name = sanitize_key($_POST['target_name'] ?? '');
$allowed = ['home', 'post_type', 'taxonomy', 'oxygen_templates', 'authors'];
if (!in_array($target_type, $allowed, true)) {
wp_die('Tipo de cache inválido.');
}
if (function_exists('set_time_limit')) {
@set_time_limit(0);
}
ignore_user_abort(true);
$result = alcastromol_generate_cache_by_target($target_type, $target_name);
$redirect = add_query_arg([
'page' => 'tailwind-cache',
'cache_target_result' => 'generated',
'cache_target_type' => $target_type,
'cache_target_name' => $target_name,
'cache_target_total' => (int) $result['total'],
'cache_target_created' => (int) $result['generated'],
'cache_target_failed' => (int) $result['failed'],
'cache_target_count' => (int) $result['count'],
], admin_url('admin.php'));
wp_safe_redirect($redirect);
exit;
});
/*
|--------------------------------------------------------------------------
| AJAX eliminar cache por tipo de contenido
|--------------------------------------------------------------------------
*/
add_action('wp_ajax_alcastromol_delete_tailwind_cache_target', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error('No tienes permisos para eliminar este cache.');
}
check_ajax_referer('alcastromol_tailwind_cache_nonce', 'nonce');
$target_type = sanitize_key($_POST['target_type'] ?? '');
$target_name = sanitize_key($_POST['target_name'] ?? '');
$allowed = ['home', 'post_type', 'taxonomy', 'oxygen_templates', 'authors'];
if (!in_array($target_type, $allowed, true)) {
wp_send_json_error('Tipo de cache inválido.');
}
$deleted = alcastromol_delete_cache_by_target($target_type, $target_name);
wp_send_json_success([
'message' => 'Cache eliminado',
'target_type' => $target_type,
'target_name' => $target_name,
'deleted' => $deleted,
'count' => alcastromol_count_cache_files_by_target($target_type, $target_name),
]);
});
/*
|--------------------------------------------------------------------------
| Página herramientas
|--------------------------------------------------------------------------
*/
add_action('admin_menu', function () {
add_submenu_page(
'alcastromol-functions',
'Cache de Tailwind',
'Cache de Tailwind',
'manage_options',
'tailwind-cache',
'alcastromol_tailwind_tools_page'
);
}, 20);
function alcastromol_tailwind_tools_page() {
$options = alcastromol_get_cache_options();
$post_types = alcastromol_detect_cacheable_post_types();
$taxonomies = alcastromol_detect_cacheable_taxonomies();
$nonce = wp_create_nonce('alcastromol_tailwind_cache_nonce');
?>
<div class="wrap">
<h1>Generar Cache Tailwind</h1>
<p>
Selecciona qué contenido quieres cachear para que Tailwind detecte clases de Gutenberg,
WooCommerce, CPTs, taxonomías y templates de Oxygen.
</p>
<hr>
<h2>Contenido cacheable detectado</h2>
<style>
.alcastromol-cache-row {
display: grid;
grid-template-columns: minmax(260px, 1fr) 110px 90px 90px;
gap: 10px;
align-items: center;
max-width: 760px;
margin-bottom: 8px;
}
.alcastromol-cache-label {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.alcastromol-cache-label code {
white-space: nowrap;
}
.alcastromol-cache-count {
font-weight: 600;
color: #1d2327;
}
@media (max-width: 782px) {
.alcastromol-cache-row {
grid-template-columns: 1fr;
padding: 10px 0;
border-bottom: 1px solid #dcdcde;
}
}
</style>
<?php if (isset($_GET['cache_target_result']) && $_GET['cache_target_result'] === 'generated') : ?>
<div class="notice notice-success inline" style="max-width:760px; margin:16px 0;">
<p>
<strong>Cache generado correctamente.</strong><br>
Tipo: <code><?php echo esc_html(sanitize_key($_GET['cache_target_name'] ?? $_GET['cache_target_type'] ?? '')); ?></code><br>
Items encontrados: <?php echo esc_html(absint($_GET['cache_target_total'] ?? 0)); ?> ·
Generados: <?php echo esc_html(absint($_GET['cache_target_created'] ?? 0)); ?> ·
Fallidos: <?php echo esc_html(absint($_GET['cache_target_failed'] ?? 0)); ?> ·
Archivos actuales: <?php echo esc_html(absint($_GET['cache_target_count'] ?? 0)); ?>
</p>
</div>
<?php endif; ?>
<form id="tailwind-cache-options-form">
<h3>General</h3>
<?php
alcastromol_render_cache_action_row([
'target_type' => 'home',
'target_name' => '',
'label' => 'Home',
'code' => '',
'input_name' => 'home',
'input_value' => '1',
'checked' => !empty($options['home']),
]);
?>
<h3>Post types / Gutenberg / WooCommerce / CPTs</h3>
<?php if (!empty($post_types)) : ?>
<?php foreach ($post_types as $post_type => $item) : ?>
<?php
alcastromol_render_cache_action_row([
'target_type' => 'post_type',
'target_name' => $post_type,
'label' => $item['label'],
'code' => $post_type,
'input_name' => 'post_types[]',
'input_value' => $post_type,
'checked' => in_array($post_type, $options['post_types'], true),
]);
?>
<?php endforeach; ?>
<?php else : ?>
<p>No se detectaron post types públicos.</p>
<?php endif; ?>
<h3>Taxonomías</h3>
<?php if (!empty($taxonomies)) : ?>
<?php foreach ($taxonomies as $taxonomy => $item) : ?>
<?php
alcastromol_render_cache_action_row([
'target_type' => 'taxonomy',
'target_name' => $taxonomy,
'label' => $item['label'],
'code' => $taxonomy,
'input_name' => 'taxonomies[]',
'input_value' => $taxonomy,
'checked' => in_array($taxonomy, $options['taxonomies'], true),
]);
?>
<?php endforeach; ?>
<?php else : ?>
<p>No se detectaron taxonomías públicas.</p>
<?php endif; ?>
<?php if (alcastromol_is_oxygen_enabled()) : ?>
<h3>Oxygen</h3>
<?php
alcastromol_render_cache_action_row([
'target_type' => 'oxygen_templates',
'target_name' => '',
'label' => 'Templates de Oxygen',
'code' => 'ct_template',
'input_name' => 'oxygen_templates',
'input_value' => '1',
'checked' => !empty($options['oxygen_templates']),
]);
?>
<?php endif; ?>
<h3>Autores</h3>
<?php
alcastromol_render_cache_action_row([
'target_type' => 'authors',
'target_name' => '',
'label' => 'Author pages',
'code' => '',
'input_name' => 'authors',
'input_value' => '1',
'checked' => !empty($options['authors']),
]);
?>
</form>
<?php alcastromol_tailwind_render_compile_section(); ?>
<p style="margin-top:20px;">
<button id="save-tailwind-cache-options" class="button">
Guardar selección
</button>
<button id="generate-tailwind-cache" class="button button-primary">
Generar cache seleccionado
</button>
<button id="delete-tailwind-cache" class="button button-secondary" style="border-color:#b32d2e; color:#b32d2e;">
Eliminar todo el cache
</button>
</p>
<pre id="cache-status" style="margin-top:20px; white-space:pre-wrap; background:#fff; padding:15px; border:1px solid #ccd0d4;"></pre>
</div>
<script>
(function(){
const nonce = '<?php echo esc_js($nonce); ?>';
const status = document.getElementById('cache-status');
const form = document.getElementById('tailwind-cache-options-form');
function getOptionsFromForm() {
const formData = new FormData(form);
const options = {
home: formData.has('home') ? 1 : 0,
post_types: formData.getAll('post_types[]'),
taxonomies: formData.getAll('taxonomies[]'),
oxygen_templates: formData.has('oxygen_templates') ? 1 : 0,
authors: formData.has('authors') ? 1 : 0
};
return options;
}
function request(action, extraData = {}) {
const body = new FormData();
body.append('action', action);
body.append('nonce', nonce);
Object.keys(extraData).forEach(key => {
if (typeof extraData[key] === 'object' && extraData[key] !== null) {
Object.keys(extraData[key]).forEach(subKey => {
const value = extraData[key][subKey];
if (Array.isArray(value)) {
value.forEach(item => {
body.append(key + '[' + subKey + '][]', item);
});
} else {
body.append(key + '[' + subKey + ']', value);
}
});
} else {
body.append(key, extraData[key]);
}
});
return fetch(ajaxurl, {
method: 'POST',
body: body
}).then(res => res.json());
}
function updateTargetCount(targetType, targetName, count) {
const selector = '[data-cache-count="' + targetType + '|' + targetName + '"]';
const countElement = document.querySelector(selector);
if (countElement) {
countElement.innerText = count + ' archivos';
}
}
function setTargetButtonsLoading(targetType, targetName, loading) {
const buttons = document.querySelectorAll('[data-target-type="' + targetType + '"][data-target-name="' + targetName + '"]');
buttons.forEach(button => {
button.disabled = loading;
});
}
document.getElementById('save-tailwind-cache-options').onclick = function(e){
e.preventDefault();
status.innerText = 'Guardando selección...';
request('alcastromol_save_tailwind_cache_options', {
options: getOptionsFromForm()
}).then(data => {
if (data.success) {
status.innerText = 'Selección guardada correctamente.';
} else {
status.innerText = 'Error: ' + data.data;
}
}).catch(() => {
status.innerText = 'Error al guardar selección.';
});
};
document.getElementById('generate-tailwind-cache').onclick = function(e){
e.preventDefault();
status.innerText = 'Guardando selección y generando cache...';
request('alcastromol_save_tailwind_cache_options', {
options: getOptionsFromForm()
}).then(saveData => {
if (!saveData.success) {
status.innerText = 'Error al guardar selección: ' + saveData.data;
return;
}
status.innerText = 'Generando cache...';
return request('alcastromol_generate_tailwind_cache');
}).then(data => {
if (!data) return;
if (data.success) {
let message =
'Cache generada correctamente.\n' +
'Total items: ' + data.data.total + '\n' +
'Productos detectados: ' + data.data.products + '\n' +
'Templates Oxygen detectados: ' + data.data.oxygen_templates + '\n' +
'Generados: ' + data.data.generated + '\n' +
'Fallidos: ' + data.data.failed + '\n\n' +
'Recarga la página para actualizar todos los contadores.';
if (data.data.failed_urls && data.data.failed_urls.length) {
message += '\n\nURLs fallidas:\n' + data.data.failed_urls.join('\n');
}
status.innerText = message;
} else {
status.innerText = 'Error: ' + data.data;
}
}).catch(() => {
status.innerText = 'Error al generar cache.';
});
};
document.getElementById('delete-tailwind-cache').onclick = function(e){
e.preventDefault();
if (!confirm('¿Seguro que quieres eliminar todo el cache de Tailwind?')) {
return;
}
status.innerText = 'Eliminando cache...';
request('alcastromol_delete_tailwind_cache')
.then(data => {
if (data.success) {
document.querySelectorAll('[data-cache-count]').forEach(element => {
element.innerText = '0 archivos';
});
status.innerText = 'Cache eliminado correctamente.\nArchivos eliminados: ' + data.data.deleted;
} else {
status.innerText = 'Error: ' + data.data;
}
})
.catch(() => {
status.innerText = 'Error al eliminar cache.';
});
};
document.querySelectorAll('.alcastromol-generate-cache-target').forEach(button => {
button.addEventListener('click', function(e){
e.preventDefault();
const targetType = this.dataset.targetType || '';
const targetName = this.dataset.targetName || '';
setTargetButtonsLoading(targetType, targetName, true);
status.innerText = 'Generando cache de este elemento... No cierres esta página.';
const postForm = document.createElement('form');
postForm.method = 'POST';
postForm.action = '<?php echo esc_js(admin_url("admin-post.php")); ?>';
const fields = {
action: 'alcastromol_generate_tailwind_cache_target_post',
nonce: nonce,
target_type: targetType,
target_name: targetName
};
Object.keys(fields).forEach(key => {
const input = document.createElement('input');
input.type = 'hidden';
input.name = key;
input.value = fields[key];
postForm.appendChild(input);
});
document.body.appendChild(postForm);
postForm.submit();
});
});
document.querySelectorAll('.alcastromol-delete-cache-target').forEach(button => {
button.addEventListener('click', function(e){
e.preventDefault();
const targetType = this.dataset.targetType || '';
const targetName = this.dataset.targetName || '';
if (!confirm('¿Seguro que quieres borrar el cache de este elemento?')) {
return;
}
setTargetButtonsLoading(targetType, targetName, true);
status.innerText = 'Borrando cache de este elemento...';
request('alcastromol_delete_tailwind_cache_target', {
target_type: targetType,
target_name: targetName
}).then(data => {
if (data.success) {
updateTargetCount(targetType, targetName, data.data.count);
status.innerText = 'Cache borrado correctamente.\nArchivos eliminados: ' + data.data.deleted + '\nArchivos actuales: ' + data.data.count;
} else {
status.innerText = 'Error: ' + data.data;
}
}).catch(() => {
status.innerText = 'Error al borrar este cache.';
}).finally(() => {
setTargetButtonsLoading(targetType, targetName, false);
});
});
});
})();
</script>
<?php
}