'Hero', 'features' => 'Features', 'services' => 'Services', 'about' => 'About', 'testimonials' => 'Testimonials', 'pricing' => 'Pricing', 'faq' => 'FAQ', 'cta' => 'Call to action', 'contact' => 'Contact', 'team' => 'Team', 'gallery' => 'Gallery', 'stats' => 'Stats', 'logos' => 'Logos', 'other' => 'Other', ); private static $printed = array(); private static $footer_js = array(); public static function init() { add_action('init', array(__CLASS__, 'register_category'), 20); add_action('save_post_wp_block', array(__CLASS__, 'on_save'), 20, 2); add_action(self::CRON_HOOK, array(__CLASS__, 'describe')); add_filter('render_block', array(__CLASS__, 'render_section_assets'), 10, 2); add_action('wp_footer', array(__CLASS__, 'print_footer_js'), 100); add_filter('block_editor_settings_all', array(__CLASS__, 'editor_styles')); add_action('enqueue_block_editor_assets', array(__CLASS__, 'enqueue_editor')); add_action('wp_ajax_aibui_save_section', array(__CLASS__, 'ajax_save_section')); add_action('wp_ajax_aibui_create_section', array(__CLASS__, 'ajax_create_section')); add_action('wp_ajax_aibui_section_ai_meta', array(__CLASS__, 'ajax_save_ai_meta')); add_action('wp_ajax_aibui_section_describe', array(__CLASS__, 'ajax_describe_now')); } public static function register_category() { if (taxonomy_exists('wp_pattern_category') && !term_exists(self::CATEGORY, 'wp_pattern_category')) { wp_insert_term('AI Builder sections', 'wp_pattern_category', array('slug' => self::CATEGORY)); } } public static function is_section($post_id) { return get_post_type($post_id) === 'wp_block' && get_post_meta($post_id, self::META_FLAG, true) === '1'; } public static function is_synced($post_id) { return get_post_meta($post_id, 'wp_pattern_sync_status', true) !== 'unsynced'; } /** @return WP_Post[] */ public static function all($limit = -1) { return get_posts(array( 'post_type' => 'wp_block', 'post_status' => 'publish', 'posts_per_page' => $limit, 'orderby' => 'modified', 'order' => 'DESC', 'meta_key' => self::META_FLAG, 'meta_value' => '1', )); } /** * Nombre de pages / articles / modèles qui utilisent la section (référence * core/block dans leur contenu). Sert à prévenir avant une suppression. */ public static function usage_count($post_id) { global $wpdb; $id = (int) $post_id; return (int) $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status IN ('publish','draft','pending','future','private') AND post_type NOT IN ('revision','wp_block') AND (post_content LIKE %s OR post_content LIKE %s)", '%' . $wpdb->esc_like('"ref":' . $id . '}') . '%', '%' . $wpdb->esc_like('"ref":' . $id . ',') . '%' )); } /** Liste compacte envoyée à l'IA à chaque génération (~30 tokens par section). */ public static function for_ai() { $out = array(); foreach (self::all(self::MAX_FOR_AI) as $post) { $description = (string) get_post_meta($post->ID, self::META_DESC, true); $out[] = array( 'id' => (int) $post->ID, 'title' => $post->post_title, 'type' => (string) get_post_meta($post->ID, self::META_TYPE, true), 'description' => $description !== '' ? $description : $post->post_title, 'synced' => self::is_synced($post->ID), ); } return $out; } // --- Création --------------------------------------------------------------- private static function check_ajax() { check_ajax_referer('aibui_nonce', 'nonce'); if (!current_user_can('edit_posts')) { wp_send_json_error(array('message' => 'Insufficient permissions'), 403); } } /** * Section créée par l'éditeur (« Save as section ») ou vide (« New section »). */ private static function insert($title, $content, $synced, $css = '', $js = '') { $post_id = wp_insert_post(array( 'post_type' => 'wp_block', 'post_status' => 'publish', 'post_title' => $title !== '' ? $title : 'Untitled section', 'post_content' => $content, ), true); if (is_wp_error($post_id)) { return $post_id; } update_post_meta($post_id, self::META_FLAG, '1'); if (!$synced) { update_post_meta($post_id, 'wp_pattern_sync_status', 'unsynced'); } if (taxonomy_exists('wp_pattern_category')) { wp_set_object_terms($post_id, self::CATEGORY, 'wp_pattern_category', true); } if ($css !== '') { update_post_meta($post_id, self::META_PAGE_CSS, $css); update_post_meta($post_id, self::META_CSS, $css); } if ($js !== '') { update_post_meta($post_id, self::META_PAGE_JS, $js); update_post_meta($post_id, self::META_JS, $js); } // save_post s'est déclenché avant la meta : on planifie ici. self::schedule_description($post_id); return $post_id; } public static function ajax_save_section() { self::check_ajax(); $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : ''; $content = isset($_POST['content']) ? wp_unslash($_POST['content']) : ''; if (!current_user_can('unfiltered_html')) { $content = wp_kses_post($content); } $synced = !empty($_POST['synced']) && $_POST['synced'] !== '0'; $css = isset($_POST['css']) ? AIBUI_CSS_Handler::sanitize_css_for_output(wp_unslash($_POST['css'])) : ''; $js = (isset($_POST['js']) && current_user_can('unfiltered_html')) ? wp_unslash($_POST['js']) : ''; if (trim($content) === '') { wp_send_json_error(array('message' => 'This block is empty.')); } $post_id = self::insert($title, $content, $synced, $css, $js); if (is_wp_error($post_id)) { wp_send_json_error(array('message' => $post_id->get_error_message())); } wp_send_json_success(array( 'id' => (int) $post_id, 'synced' => $synced, 'editUrl' => get_edit_post_link($post_id, 'raw'), 'css' => $css, )); } public static function ajax_create_section() { self::check_ajax(); $post_id = self::insert('New section', '', true); if (is_wp_error($post_id)) { wp_send_json_error(array('message' => $post_id->get_error_message())); } wp_send_json_success(array('editUrl' => get_edit_post_link($post_id, 'raw'))); } /** Description / type corrigés à la main : plus jamais régénérés automatiquement. */ public static function ajax_save_ai_meta() { self::check_ajax(); $post_id = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0; if (!$post_id || !current_user_can('edit_post', $post_id) || get_post_type($post_id) !== 'wp_block') { wp_send_json_error(array('message' => 'Insufficient permissions'), 403); } update_post_meta($post_id, self::META_FLAG, '1'); $description = isset($_POST['description']) ? sanitize_textarea_field(wp_unslash($_POST['description'])) : ''; $type = isset($_POST['type']) ? sanitize_key(wp_unslash($_POST['type'])) : ''; update_post_meta($post_id, self::META_DESC, mb_substr($description, 0, 300)); update_post_meta($post_id, self::META_TYPE, isset(self::TYPES[$type]) ? $type : 'other'); update_post_meta($post_id, self::META_MANUAL, $description !== '' ? '1' : ''); update_post_meta($post_id, self::META_STATUS, 'done'); wp_send_json_success(self::ai_meta($post_id)); } public static function ajax_describe_now() { self::check_ajax(); $post_id = isset($_POST['post_id']) ? (int) $_POST['post_id'] : 0; if (!$post_id || !current_user_can('edit_post', $post_id) || !self::is_section($post_id)) { wp_send_json_error(array('message' => 'Insufficient permissions'), 403); } delete_post_meta($post_id, self::META_MANUAL); $ok = self::describe($post_id, true); if (!$ok) { wp_send_json_error(array('message' => 'The description could not be generated right now. It will be retried automatically.')); } wp_send_json_success(self::ai_meta($post_id)); } public static function ai_meta($post_id) { return array( 'description' => (string) get_post_meta($post_id, self::META_DESC, true), 'type' => (string) get_post_meta($post_id, self::META_TYPE, true), 'manual' => get_post_meta($post_id, self::META_MANUAL, true) === '1', 'status' => (string) get_post_meta($post_id, self::META_STATUS, true), 'synced' => self::is_synced($post_id), ); } // --- Description en arrière-plan (Haiku, via l'API) -------------------------- private static function content_hash($post) { return md5($post->post_title . "\n" . $post->post_content); } public static function on_save($post_id, $post) { if (wp_is_post_revision($post_id) || $post->post_status !== 'publish' || !self::is_section($post_id)) { return; } self::schedule_description($post_id); } /** Planifie la description si le contenu a changé et qu'elle n'est pas manuelle. */ public static function schedule_description($post_id) { $post = get_post($post_id); if (!$post || trim($post->post_content) === '') { return; } if (get_post_meta($post_id, self::META_MANUAL, true) === '1') { return; } if (get_post_meta($post_id, self::META_HASH, true) === self::content_hash($post)) { return; } update_post_meta($post_id, self::META_STATUS, 'pending'); update_post_meta($post_id, self::META_ATTEMPTS, 0); if (!wp_next_scheduled(self::CRON_HOOK, array((int) $post_id))) { wp_schedule_single_event(time() + 5, self::CRON_HOOK, array((int) $post_id)); } } /** * POST /sections/describe { title, content, locale, types } * → { description, type }. Réessayé 3 fois (1 h d'écart) en cas d'échec. */ public static function describe($post_id, $now = false) { $post = get_post($post_id); if (!$post || !self::is_section($post_id)) { return false; } if (!$now && get_post_meta($post_id, self::META_MANUAL, true) === '1') { return false; } $jwt = get_option('aibui_jwt_token', ''); $response = $jwt ? wp_remote_post(aibui_api_url('/sections/describe'), array( 'timeout' => 30, 'headers' => aibui_api_headers(array( 'Authorization' => 'Bearer ' . $jwt, 'Content-Type' => 'application/json', )), 'body' => wp_json_encode(array( 'title' => $post->post_title, 'content' => mb_substr($post->post_content, 0, self::MAX_DESCRIBE_CHARS), 'locale' => get_locale(), 'types' => array_keys(self::TYPES), )), )) : null; $decoded = ($response && !is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) ? json_decode(wp_remote_retrieve_body($response), true) : null; if (!is_array($decoded) || empty($decoded['description']) || !is_string($decoded['description'])) { $attempts = (int) get_post_meta($post_id, self::META_ATTEMPTS, true) + 1; update_post_meta($post_id, self::META_ATTEMPTS, $attempts); update_post_meta($post_id, self::META_STATUS, 'failed'); if (!$now && $attempts < 3) { wp_schedule_single_event(time() + HOUR_IN_SECONDS, self::CRON_HOOK, array((int) $post_id)); } return false; } $type = isset($decoded['type']) ? sanitize_key($decoded['type']) : 'other'; update_post_meta($post_id, self::META_DESC, mb_substr(sanitize_textarea_field($decoded['description']), 0, 300)); update_post_meta($post_id, self::META_TYPE, isset(self::TYPES[$type]) ? $type : 'other'); update_post_meta($post_id, self::META_HASH, self::content_hash($post)); update_post_meta($post_id, self::META_STATUS, 'done'); delete_post_meta($post_id, self::META_ATTEMPTS); return true; } // --- CSS / JS ------------------------------------------------------------------ /** Sur le site : CSS de la section avant son contenu (une fois par page), JS en pied de page. */ public static function render_section_assets($block_content, $block) { if (is_admin() || !is_array($block) || ($block['blockName'] ?? '') !== 'core/block' || empty($block['attrs']['ref'])) { return $block_content; } $ref = (int) $block['attrs']['ref']; if (isset(self::$printed[$ref]) || !self::is_section($ref)) { return $block_content; } self::$printed[$ref] = true; $css = (string) get_post_meta($ref, self::META_CSS, true); $js = (string) get_post_meta($ref, self::META_JS, true); if ($js !== '') { self::$footer_js[$ref] = $js; } if ($css === '') { return $block_content; } return '' . $block_content; } public static function print_footer_js() { foreach (self::$footer_js as $ref => $js) { echo ''; } } /** Aperçu dans l'éditeur : CSS de toutes les sections dans le canvas. */ public static function editor_styles($settings) { $css = ''; foreach (self::all(100) as $post) { $part = (string) get_post_meta($post->ID, self::META_CSS, true); if ($part !== '' && strlen($css) + strlen($part) < self::MAX_EDITOR_CSS) { $css .= "\n" . $part; } } if ($css !== '') { $settings['styles'][] = array('css' => $css, '__unstableType' => 'user', 'source' => 'aibui-sections'); } return $settings; } public static function enqueue_editor() { $screen = function_exists('get_current_screen') ? get_current_screen() : null; if (!$screen || $screen->base !== 'post') { return; } $post_id = isset($_GET['post']) ? (int) $_GET['post'] : 0; wp_enqueue_script( 'aibui-sections-editor', plugin_dir_url(dirname(__FILE__)) . 'assets/js/sections-editor.js', array('wp-plugins', 'wp-element', 'wp-components', 'wp-data', 'wp-blocks', 'wp-editor', 'wp-block-editor', 'wp-notices'), AIBUI_VERSION, true ); wp_localize_script('aibui-sections-editor', 'aibuiSectionsVars', array( 'ajaxurl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('aibui_nonce'), 'sectionsUrl' => admin_url('admin.php?page=aibui-sections'), 'types' => self::TYPES, 'current' => ($post_id && self::is_section($post_id)) ? array_merge(array('id' => $post_id), self::ai_meta($post_id)) : null, )); } } AIBUI_Sections::init();