__( 'AI Content Creator', 'ai-content-creator' ), 'description' => __( 'Abilities for generating and managing AI-created article drafts.', 'ai-content-creator' ), ) ); } add_action( 'wp_abilities_api_categories_init', 'aicc_register_ability_category' ); /** * Registra las habilidades del plugin cuando la API está disponible. */ function aicc_register_abilities() { aicc_call_if_exists( 'wp_register_ability', 'ai-content-creator/get-plugin-settings-summary', array( 'label' => __( 'Get plugin settings summary', 'ai-content-creator' ), 'description' => __( 'Returns a safe summary of the AI Content Creator settings without exposing API keys.', 'ai-content-creator' ), 'category' => 'ai-content-creator', 'output_schema' => aicc_get_plugin_settings_summary_schema(), 'execute_callback' => 'aicc_get_plugin_settings_summary', 'permission_callback' => 'aicc_can_read_plugin_settings_summary', 'meta' => array( 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ), 'show_in_rest' => false, ), ) ); aicc_call_if_exists( 'wp_register_ability', 'ai-content-creator/get-generation', array( 'label' => __( 'Get generation', 'ai-content-creator' ), 'description' => __( 'Returns a stored AI content generation without exposing raw API requests or responses.', 'ai-content-creator' ), 'category' => 'ai-content-creator', 'input_schema' => aicc_get_generation_input_schema(), 'output_schema' => aicc_get_generation_output_schema(), 'execute_callback' => 'aicc_get_generation', 'permission_callback' => 'aicc_can_read_generation', 'meta' => array( 'annotations' => array( 'readonly' => true, 'destructive' => false, 'idempotent' => true, ), 'show_in_rest' => false, ), ) ); aicc_call_if_exists( 'wp_register_ability', 'ai-content-creator/generate-article', array( 'label' => __( 'Generate article', 'ai-content-creator' ), 'description' => __( 'Generates and stores a new AI-created article using the existing plugin flow.', 'ai-content-creator' ), 'category' => 'ai-content-creator', 'input_schema' => aicc_obtener_esquema_entrada_generar_articulo(), 'output_schema' => aicc_get_generation_output_schema(), 'execute_callback' => 'aicc_generar_articulo_habilidad', 'permission_callback' => 'aicc_puede_generar_articulo_habilidad', 'meta' => array( 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => false, ), 'show_in_rest' => false, ), ) ); aicc_call_if_exists( 'wp_register_ability', 'ai-content-creator/create-draft-from-generation', array( 'label' => __( 'Create draft from generation', 'ai-content-creator' ), 'description' => __( 'Creates a WordPress draft post from a stored AI content generation.', 'ai-content-creator' ), 'category' => 'ai-content-creator', 'input_schema' => aicc_obtener_esquema_entrada_crear_borrador(), 'output_schema' => aicc_obtener_esquema_salida_crear_borrador(), 'execute_callback' => 'aicc_crear_borrador_habilidad', 'permission_callback' => 'aicc_puede_crear_borrador_habilidad', 'meta' => array( 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => true, ), 'show_in_rest' => false, ), ) ); aicc_call_if_exists( 'wp_register_ability', 'ai-content-creator/reprocess-generation', array( 'label' => __( 'Reprocess generation', 'ai-content-creator' ), 'description' => __( 'Repeats internal post-processing and validation for a stored AI content generation.', 'ai-content-creator' ), 'category' => 'ai-content-creator', 'input_schema' => aicc_get_generation_input_schema(), 'output_schema' => aicc_get_generation_output_schema(), 'execute_callback' => 'aicc_reprocesar_generacion_habilidad', 'permission_callback' => 'aicc_can_read_generation', 'meta' => array( 'annotations' => array( 'readonly' => false, 'destructive' => false, 'idempotent' => false, ), 'show_in_rest' => false, ), ) ); } add_action( 'wp_abilities_api_init', 'aicc_register_abilities' ); /** * Comprueba si el usuario actual puede leer el resumen de ajustes del plugin. * * @return bool Verdadero si el usuario puede leer el resumen. */ function aicc_can_read_plugin_settings_summary() { return current_user_can( 'manage_options' ); } /** * Devuelve un resumen seguro de los ajustes del plugin. * * @return array Resumen de ajustes sin claves API ni secretos. */ function aicc_get_plugin_settings_summary() { $options = get_option( 'aicc_settings' ); if ( ! is_array( $options ) ) { $options = array(); } $openai_api_key = ''; if ( isset( $options['aicc_apikoai'] ) && is_string( $options['aicc_apikoai'] ) ) { $openai_api_key = trim( $options['aicc_apikoai'] ); } return array( 'model' => isset( $options['aicc_modelo'] ) ? sanitize_text_field( $options['aicc_modelo'] ) : 'gpt-6.1-sol', 'length' => isset( $options['aicc_longitud'] ) ? absint( $options['aicc_longitud'] ) : 500, 'timeout' => isset( $options['aicc_timeout'] ) ? absint( $options['aicc_timeout'] ) : 600, 'language' => isset( $options['aicc_idioma'] ) ? sanitize_text_field( $options['aicc_idioma'] ) : '', 'tone' => isset( $options['aicc_tono'] ) ? sanitize_text_field( $options['aicc_tono'] ) : '', 'table_of_contents_enabled' => ! empty( $options['aicc_tablacontenidos'] ), 'editors_can_create' => ! empty( $options['aicc_editorescrean'] ), 'openai_api_key_configured' => '' !== $openai_api_key, ); } /** * Devuelve el esquema de salida para el resumen seguro de ajustes. * * @return array Esquema JSON de la salida de la habilidad. */ function aicc_get_plugin_settings_summary_schema() { return array( 'type' => 'object', 'properties' => array( 'model' => array( 'type' => 'string', 'description' => __( 'Configured AI model.', 'ai-content-creator' ), ), 'length' => array( 'type' => 'integer', 'description' => __( 'Configured article length in words.', 'ai-content-creator' ), ), 'timeout' => array( 'type' => 'integer', 'description' => __( 'Configured generation timeout in seconds.', 'ai-content-creator' ), ), 'language' => array( 'type' => 'string', 'description' => __( 'Configured article language code.', 'ai-content-creator' ), ), 'tone' => array( 'type' => 'string', 'description' => __( 'Configured article tone.', 'ai-content-creator' ), ), 'table_of_contents_enabled' => array( 'type' => 'boolean', 'description' => __( 'Whether generated articles request a table of contents.', 'ai-content-creator' ), ), 'editors_can_create' => array( 'type' => 'boolean', 'description' => __( 'Whether editors can create articles with AI.', 'ai-content-creator' ), ), 'openai_api_key_configured' => array( 'type' => 'boolean', 'description' => __( 'Whether an OpenAI API key is configured.', 'ai-content-creator' ), ), ), 'required' => array( 'model', 'length', 'timeout', 'language', 'tone', 'table_of_contents_enabled', 'editors_can_create', 'openai_api_key_configured', ), 'additionalProperties' => false, ); } /** * Comprueba si el usuario actual puede leer una generación almacenada. * * Replica la política de creación sin cargar la pantalla de administración. * * @return bool Verdadero si el usuario puede leer generaciones. */ function aicc_can_read_generation() { $options = get_option( 'aicc_settings' ); if ( is_array( $options ) && ! empty( $options['aicc_editorescrean'] ) ) { return current_user_can( 'edit_posts' ); } return current_user_can( 'manage_options' ); } /** * Devuelve una generación almacenada como salida segura de habilidad. * * @param array $input Datos de entrada validados por la habilidad. * @return array|WP_Error Datos de la generación o error. */ function aicc_get_generation( $input ) { $generation_id = 0; if ( is_array( $input ) && isset( $input['generation_id'] ) ) { $generation_id = absint( $input['generation_id'] ); } if ( $generation_id < 1 ) { return new WP_Error( 'aicc_invalid_generation_id', __( 'The generation ID is not valid.', 'ai-content-creator' ) ); } aicc_load_generation_dependencies(); $generation = new AICC_Generacion(); if ( ! $generation->cargar( $generation_id ) ) { return new WP_Error( 'aicc_generation_not_found', __( 'Unable to load the specified article.', 'ai-content-creator' ) ); } return aicc_generation_to_ability_output( $generation ); } /** * Carga las dependencias necesarias para leer generaciones fuera del admin. */ function aicc_load_generation_dependencies() { require_once dirname( __DIR__ ) . '/bbdd.php'; require_once dirname( __DIR__ ) . '/classes/class-aicc-generacion.php'; } /** * Comprueba si el usuario actual puede generar articulos desde una habilidad. * * Replica la politica configurable del flujo de administracion sin cargar la * pantalla de ajustes fuera del admin. * * @return bool Verdadero si el usuario puede generar articulos. */ function aicc_puede_generar_articulo_habilidad() { $options = get_option( 'aicc_settings' ); if ( is_array( $options ) && ! empty( $options['aicc_editorescrean'] ) ) { return current_user_can( 'edit_posts' ); } return current_user_can( 'manage_options' ); } /** * Genera un articulo desde la Abilities API. * * @param array $input Datos de entrada validados por la habilidad. * @return array|WP_Error Datos de la generacion o error. */ function aicc_generar_articulo_habilidad( $input ) { if ( ! is_array( $input ) ) { $input = array(); } aicc_cargar_dependencias_generacion_habilidad(); $generation = aicc_generar_articulo( array( 'titulo' => isset( $input['titulo'] ) ? $input['titulo'] : '', 'contexto' => isset( $input['contexto'] ) ? $input['contexto'] : '', 'directrices_adicionales' => isset( $input['directrices_adicionales'] ) ? $input['directrices_adicionales'] : '', ) ); if ( is_wp_error( $generation ) ) { return $generation; } return aicc_generation_to_ability_output( $generation ); } /** * Carga las dependencias necesarias para generar articulos fuera del admin. */ function aicc_cargar_dependencias_generacion_habilidad() { require_once dirname( __DIR__ ) . '/admin/configuracion.php'; require_once dirname( __DIR__ ) . '/bbdd.php'; require_once dirname( __DIR__ ) . '/classes/class-aicc-generacion.php'; require_once dirname( __DIR__ ) . '/admin/posproduccion.php'; require_once dirname( __DIR__ ) . '/admin/funciones.php'; require_once dirname( __DIR__ ) . '/admin/idiomas.php'; require_once dirname( __DIR__ ) . '/includes/generacion.php'; } /** * Comprueba si el usuario actual puede crear borradores desde una habilidad. * * @return bool Verdadero si el usuario puede crear borradores. */ function aicc_puede_crear_borrador_habilidad() { return current_user_can( 'edit_posts' ); } /** * Crea un borrador desde una generacion almacenada. * * @param array $input Datos de entrada validados por la habilidad. * @return array|WP_Error Datos del borrador o error. */ function aicc_crear_borrador_habilidad( $input ) { $generation_id = 0; if ( is_array( $input ) && isset( $input['generation_id'] ) ) { $generation_id = absint( $input['generation_id'] ); } if ( $generation_id < 1 ) { return new WP_Error( 'aicc_invalid_generation_id', __( 'The generation ID is not valid.', 'ai-content-creator' ) ); } $aceptar_contenido_defectuoso = false; if ( is_array( $input ) && isset( $input['aceptar_contenido_defectuoso'] ) ) { $aceptar_contenido_defectuoso = (bool) $input['aceptar_contenido_defectuoso']; } aicc_cargar_dependencias_generacion_habilidad(); $generation = new AICC_Generacion(); if ( ! $generation->cargar( $generation_id ) ) { return new WP_Error( 'aicc_generation_not_found', __( 'Unable to load the specified article.', 'ai-content-creator' ) ); } if ( $generation->publicada_post_id() ) { return aicc_salida_borrador_habilidad( $generation, true ); } if ( ! $generation->contenido() ) { return new WP_Error( 'aicc_generation_without_content', __( 'The stored generation has no content to create a draft.', 'ai-content-creator' ) ); } if ( ! $generation->valida() && ! $aceptar_contenido_defectuoso ) { return new WP_Error( 'aicc_defective_content_not_accepted', __( 'The generated content has validation errors. Confirm that defective content is accepted to create a draft.', 'ai-content-creator' ) ); } $post_id = $generation->crear_borrador(); if ( ! $post_id ) { return new WP_Error( 'aicc_draft_creation_failed', __( 'Failed to create the draft.', 'ai-content-creator' ) ); } return aicc_salida_borrador_habilidad( $generation, false ); } /** * Convierte la generacion con borrador en salida de habilidad. * * @param AICC_Generacion $generation Generacion almacenada. * @param bool $already_created Indica si el borrador ya existia. * @return array Datos del borrador. */ function aicc_salida_borrador_habilidad( $generation, $already_created ) { $draft_post_id = absint( $generation->publicada_post_id() ); $draft_edit_url = ''; $status = ''; if ( $draft_post_id ) { $status = get_post_status( $draft_post_id ); if ( current_user_can( 'edit_post', $draft_post_id ) ) { $draft_edit_url = get_edit_post_link( $draft_post_id, 'raw' ); } } return array( 'generation_id' => absint( $generation->id() ), 'draft_post_id' => $draft_post_id, 'draft_edit_url' => $draft_edit_url ? $draft_edit_url : '', 'status' => $status ? (string) $status : '', 'already_created' => (bool) $already_created, ); } /** * Reprocesa una generacion almacenada desde la Abilities API. * * @param array $input Datos de entrada validados por la habilidad. * @return array|WP_Error Datos de la generacion reprocesada o error. */ function aicc_reprocesar_generacion_habilidad( $input ) { $generation_id = 0; if ( is_array( $input ) && isset( $input['generation_id'] ) ) { $generation_id = absint( $input['generation_id'] ); } if ( $generation_id < 1 ) { return new WP_Error( 'aicc_invalid_generation_id', __( 'The generation ID is not valid.', 'ai-content-creator' ) ); } aicc_cargar_dependencias_generacion_habilidad(); $generation = new AICC_Generacion(); if ( ! $generation->cargar( $generation_id ) ) { return new WP_Error( 'aicc_generation_not_found', __( 'Unable to load the specified article.', 'ai-content-creator' ) ); } $generation->procesar_respuesta_auto(); $generation->validar_contenido_auto(); if ( ! $generation->grabar() ) { return new WP_Error( 'aicc_reprocess_save_failed', __( 'Failed to save the reprocessing result.', 'ai-content-creator' ) ); } return aicc_generation_to_ability_output( $generation ); } /** * Convierte una generación en una salida segura para Abilities API. * * @param AICC_Generacion $generation Generación cargada desde la base de datos. * @return array Datos seguros de la generación. */ function aicc_generation_to_ability_output( $generation ) { $draft_post_id = absint( $generation->publicada_post_id() ); $draft_edit_url = ''; if ( $draft_post_id && current_user_can( 'edit_post', $draft_post_id ) ) { $draft_edit_url = get_edit_post_link( $draft_post_id, 'raw' ); } return array( 'generation_id' => absint( $generation->id() ), 'date' => (string) $generation->fecha(), 'model' => (string) $generation->modelo(), 'language' => (string) $generation->idioma(), 'requested_length' => absint( $generation->longitud_solicitada() ), 'tone' => (string) $generation->tono(), 'title' => (string) $generation->titulo(), 'context' => (string) $generation->contexto(), 'additional_guidelines' => (string) $generation->directrices_adicionales(), 'content' => (string) $generation->contenido(), 'valid' => (bool) $generation->valida(), 'errors' => aicc_normalize_ability_string_list( $generation->validacion_errores() ), 'warnings' => aicc_normalize_ability_string_list( $generation->validacion_advertencias() ), 'notifications' => aicc_normalize_ability_string_list( $generation->validacion_notificaciones() ), 'edit_generation_url' => admin_url( add_query_arg( array( 'page' => 'aicc_articles', 'id' => absint( $generation->id() ), 'accion' => 'ver', ), 'admin.php' ) ), 'draft_post_id' => $draft_post_id, 'draft_edit_url' => $draft_edit_url ? $draft_edit_url : '', ); } /** * Normaliza una lista de textos para salida de la habilidad. * * @param mixed $items Lista de valores de origen. * @return array Lista de textos saneados. */ function aicc_normalize_ability_string_list( $items ) { if ( ! is_array( $items ) ) { return array(); } $strings = array(); foreach ( $items as $item ) { if ( is_scalar( $item ) ) { $strings[] = sanitize_text_field( (string) $item ); } } return $strings; } /** * Devuelve el esquema de entrada para consultar una generación. * * @return array Esquema JSON de entrada. */ function aicc_get_generation_input_schema() { return array( 'type' => 'object', 'properties' => array( 'generation_id' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'Stored generation ID.', 'ai-content-creator' ), ), ), 'required' => array( 'generation_id' ), 'additionalProperties' => false, ); } /** * Devuelve el esquema de entrada para generar un articulo. * * @return array Esquema JSON de entrada. */ function aicc_obtener_esquema_entrada_generar_articulo() { return array( 'type' => 'object', 'properties' => array( 'titulo' => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 255, 'description' => __( 'Article title to generate.', 'ai-content-creator' ), ), 'contexto' => array( 'type' => 'string', 'maxLength' => 512, 'description' => __( 'Optional article context.', 'ai-content-creator' ), ), 'directrices_adicionales' => array( 'type' => 'string', 'maxLength' => 1024, 'description' => __( 'Optional additional guidelines, one per line.', 'ai-content-creator' ), ), ), 'required' => array( 'titulo' ), 'additionalProperties' => false, ); } /** * Devuelve el esquema de entrada para crear un borrador. * * @return array Esquema JSON de entrada. */ function aicc_obtener_esquema_entrada_crear_borrador() { return array( 'type' => 'object', 'properties' => array( 'generation_id' => array( 'type' => 'integer', 'minimum' => 1, 'description' => __( 'Stored generation ID.', 'ai-content-creator' ), ), 'aceptar_contenido_defectuoso' => array( 'type' => 'boolean', 'description' => __( 'Whether to create a draft even when validation errors were detected.', 'ai-content-creator' ), ), ), 'required' => array( 'generation_id' ), 'additionalProperties' => false, ); } /** * Devuelve el esquema de salida para crear un borrador. * * @return array Esquema JSON de salida. */ function aicc_obtener_esquema_salida_crear_borrador() { return array( 'type' => 'object', 'properties' => array( 'generation_id' => array( 'type' => 'integer', 'description' => __( 'Stored generation ID.', 'ai-content-creator' ), ), 'draft_post_id' => array( 'type' => 'integer', 'description' => __( 'Draft post ID created from the generation.', 'ai-content-creator' ), ), 'draft_edit_url' => array( 'type' => 'string', 'description' => __( 'Admin URL for editing the draft when available.', 'ai-content-creator' ), ), 'status' => array( 'type' => 'string', 'description' => __( 'Current post status for the draft.', 'ai-content-creator' ), ), 'already_created' => array( 'type' => 'boolean', 'description' => __( 'Whether the draft already existed before this ability call.', 'ai-content-creator' ), ), ), 'required' => array( 'generation_id', 'draft_post_id', 'draft_edit_url', 'status', 'already_created', ), 'additionalProperties' => false, ); } /** * Devuelve el esquema de salida para consultar una generación. * * @return array Esquema JSON de salida. */ function aicc_get_generation_output_schema() { return array( 'type' => 'object', 'properties' => array( 'generation_id' => array( 'type' => 'integer', 'description' => __( 'Stored generation ID.', 'ai-content-creator' ), ), 'date' => array( 'type' => 'string', 'description' => __( 'Generation date.', 'ai-content-creator' ), ), 'model' => array( 'type' => 'string', 'description' => __( 'AI model used for the generation.', 'ai-content-creator' ), ), 'language' => array( 'type' => 'string', 'description' => __( 'Language requested for the generation.', 'ai-content-creator' ), ), 'requested_length' => array( 'type' => 'integer', 'description' => __( 'Requested article length in words.', 'ai-content-creator' ), ), 'tone' => array( 'type' => 'string', 'description' => __( 'Tone requested for the generation.', 'ai-content-creator' ), ), 'title' => array( 'type' => 'string', 'description' => __( 'Generated article title.', 'ai-content-creator' ), ), 'context' => array( 'type' => 'string', 'description' => __( 'Context provided for the generation.', 'ai-content-creator' ), ), 'additional_guidelines' => array( 'type' => 'string', 'description' => __( 'Additional guidelines provided for the generation.', 'ai-content-creator' ), ), 'content' => array( 'type' => 'string', 'description' => __( 'Generated article content.', 'ai-content-creator' ), ), 'valid' => array( 'type' => 'boolean', 'description' => __( 'Whether the generated content passed validation.', 'ai-content-creator' ), ), 'errors' => aicc_get_string_array_schema( __( 'Validation errors.', 'ai-content-creator' ) ), 'warnings' => aicc_get_string_array_schema( __( 'Validation warnings.', 'ai-content-creator' ) ), 'notifications' => aicc_get_string_array_schema( __( 'Validation notifications.', 'ai-content-creator' ) ), 'edit_generation_url' => array( 'type' => 'string', 'description' => __( 'Admin URL for viewing the stored generation.', 'ai-content-creator' ), ), 'draft_post_id' => array( 'type' => 'integer', 'description' => __( 'Draft post ID created from the generation, or zero when none exists.', 'ai-content-creator' ), ), 'draft_edit_url' => array( 'type' => 'string', 'description' => __( 'Admin URL for editing the draft when available.', 'ai-content-creator' ), ), ), 'required' => array( 'generation_id', 'date', 'model', 'language', 'requested_length', 'tone', 'title', 'context', 'additional_guidelines', 'content', 'valid', 'errors', 'warnings', 'notifications', 'edit_generation_url', 'draft_post_id', 'draft_edit_url', ), 'additionalProperties' => false, ); } /** * Devuelve un esquema reutilizable para listas de textos. * * @param string $description Descripción del campo. * @return array Esquema JSON de lista de textos. */ function aicc_get_string_array_schema( $description ) { return array( 'type' => 'array', 'description' => $description, 'items' => array( 'type' => 'string', ), ); }