API
* Settings), and the "no provider connected" notice.
*
* @package AI_Content_Generator_For_WooCommerce
* @subpackage Admin/Modules/SetupWizard
* @since 1.1.7
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class WTOFE_Setup_Wizard {
const PAGE_SLUG = 'wtofe-ai-setup';
const COMPLETED_OPTION = 'wtofe_ai_setup_completed';
const FINISH_ACTION = 'wtofe_ai_setup_finish';
/** @var string Hook suffix returned by add_submenu_page(). */
private static $hook_suffix = '';
// -------------------------------------------------------------------------
// Bootstrap
// -------------------------------------------------------------------------
/**
* Registers all admin hooks for this module.
* Called once from the main plugin class.
*/
public static function register_hooks() {
add_action( 'admin_menu', array( __CLASS__, 'add_page' ) );
add_action( 'current_screen', array( __CLASS__, 'maybe_remove_notices' ) );
add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_scripts' ) );
add_action( 'admin_post_' . self::FINISH_ACTION, array( __CLASS__, 'handle_finish' ) );
add_filter( 'parent_file', array( __CLASS__, 'highlight_parent_menu' ) );
add_filter( 'submenu_file', array( __CLASS__, 'highlight_submenu' ) );
}
/**
* Whether the activation redirect should land on the wizard rather than
* the settings page: only until the wizard is finished or skipped, and
* only while no provider is connected (existing setups skip straight to
* the settings page, as before).
*
* @return bool
*/
public static function should_redirect() {
return ! get_option( self::COMPLETED_OPTION, false )
&& ! AI_Content_Generator_For_WooCommerce_Helper::has_active_connector();
}
/** @return string */
public static function get_url() {
return admin_url( 'admin.php?page=' . self::PAGE_SLUG );
}
/**
* Link that marks the wizard as done, then redirects.
*
* @param string $redirect_to Admin URL to land on.
* @return string
*/
public static function get_finish_url( $redirect_to ) {
return wp_nonce_url(
add_query_arg(
array(
'action' => self::FINISH_ACTION,
'redirect_to' => rawurlencode( $redirect_to ),
),
admin_url( 'admin-post.php' )
),
self::FINISH_ACTION
);
}
// -------------------------------------------------------------------------
// Page
// -------------------------------------------------------------------------
/** Registers the page without a menu entry. */
public static function add_page() {
self::$hook_suffix = (string) add_submenu_page(
'',
__( 'AI Content Generator Setup', 'ai-content-generator-for-woocommerce' ),
'',
'manage_woocommerce',
self::PAGE_SLUG,
array( __CLASS__, 'render_page' )
);
// A page without a menu entry gets no admin
from core.
add_action( 'load-' . self::$hook_suffix, static function () {
$GLOBALS['title'] = __( 'AI Content Generator Setup', 'ai-content-generator-for-woocommerce' ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
} );
}
/** @return bool */
private static function is_wizard_screen() {
$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
return $screen && '' !== self::$hook_suffix && self::$hook_suffix === $screen->id;
}
/**
* Keeps the wizard focused: other plugins' notices (and our own "no
* provider connected" notice, which the wizard is fixing) are dropped on
* this one screen.
*/
public static function maybe_remove_notices() {
if ( ! self::is_wizard_screen() ) {
return;
}
remove_all_actions( 'admin_notices' );
remove_all_actions( 'all_admin_notices' );
}
/** Keeps WooCommerce › AI Content Generator highlighted while on the wizard. */
public static function highlight_parent_menu( $parent_file ) {
if ( ! self::is_wizard_screen() ) {
return $parent_file;
}
// Right after this filter, core's get_admin_page_parent() looks the
// page up in $submenu, finds it under the empty parent, and resets
// the highlight. Access checks are done by now, so the entry can go.
remove_submenu_page( '', self::PAGE_SLUG );
return 'woocommerce';
}
/** @see highlight_parent_menu() */
public static function highlight_submenu( $submenu_file ) {
return self::is_wizard_screen() ? 'wc-ai-content-generator' : $submenu_file;
}
public static function enqueue_scripts( $hook ) {
if ( '' === self::$hook_suffix || $hook !== self::$hook_suffix ) {
return;
}
AI_Content_Generator_For_WooCommerce_Admin::enqueue_connection_test_script();
wp_enqueue_style(
'wtofe-setup-wizard',
WTOFE_AI_PLUGIN_URL . 'admin/modules/setup-wizard/assets/css/setup-wizard.css',
array(),
WTOFE_AI_VERSION
);
wp_enqueue_script(
'wtofe-setup-wizard',
WTOFE_AI_PLUGIN_URL . 'admin/modules/setup-wizard/assets/js/setup-wizard.js',
array( 'jquery', 'wp-api-fetch', 'wtofe-connection-test' ),
WTOFE_AI_VERSION,
true
);
wp_localize_script( 'wtofe-setup-wizard', 'wtofeSetup', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'saveKeyNonce' => wp_create_nonce( 'wtofe_save_api_key' ),
'i18n' => array(
'installing' => __( 'Installing…', 'ai-content-generator-for-woocommerce' ),
'activating' => __( 'Activating…', 'ai-content-generator-for-woocommerce' ),
'connecting' => __( 'Checking key…', 'ai-content-generator-for-woocommerce' ),
'enterKey' => __( 'Paste your API key first.', 'ai-content-generator-for-woocommerce' ),
/* translators: %s: provider name, e.g. OpenAI */
'keyRejected' => __( 'Couldn\'t verify this key with %s. Check that you copied all of it and that the account has API access, then try again.', 'ai-content-generator-for-woocommerce' ),
'keyNotSaved' => __( 'The key couldn\'t be saved because the provider plugin isn\'t active. Reload the page and try again.', 'ai-content-generator-for-woocommerce' ),
'installFailed' => __( 'Couldn\'t install the provider plugin.', 'ai-content-generator-for-woocommerce' ),
'activateFailed' => __( 'Couldn\'t activate the provider plugin.', 'ai-content-generator-for-woocommerce' ),
'requestFailed' => __( 'Something went wrong. Reload the page and try again.', 'ai-content-generator-for-woocommerce' ),
),
) );
}
/** Renders the wizard. */
public static function render_page() {
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to access this page.', 'ai-content-generator-for-woocommerce' ) );
}
$wtofe_setup = array(
'connectors_available' => AI_Content_Generator_For_WooCommerce_Helper::has_ai_connectors_screen() && function_exists( 'wp_get_connectors' ),
'providers' => self::get_providers(),
'custom_key' => self::get_custom_key_state(),
'can_install' => current_user_can( 'install_plugins' ) && wp_is_file_mod_allowed( 'install_plugins' ),
'can_activate' => current_user_can( 'activate_plugins' ),
'can_manage_keys' => current_user_can( 'manage_options' ),
'connectors_url' => admin_url( 'options-connectors.php' ),
'settings_url' => admin_url( 'admin.php?page=wc-ai-content-generator' ),
'products_url' => admin_url( 'edit.php?post_type=product' ),
'guide_url' => AI_Content_Generator_For_WooCommerce_Helper::get_user_guide_url(),
);
require WTOFE_AI_PLUGIN_DIR . 'admin/modules/setup-wizard/partials/setup-wizard.php';
}
/**
* Marks the wizard as done (finished or skipped) and redirects.
* The flag only stops the activation redirect; the wizard stays reachable.
*/
public static function handle_finish() {
check_admin_referer( self::FINISH_ACTION );
if ( ! current_user_can( 'manage_woocommerce' ) ) {
wp_die( esc_html__( 'Sorry, you are not allowed to do that.', 'ai-content-generator-for-woocommerce' ) );
}
update_option( self::COMPLETED_OPTION, true );
$redirect_to = isset( $_GET['redirect_to'] ) ? esc_url_raw( wp_unslash( $_GET['redirect_to'] ) ) : '';
wp_safe_redirect( $redirect_to ? $redirect_to : admin_url( 'admin.php?page=wc-ai-content-generator' ) );
exit;
}
// -------------------------------------------------------------------------
// Provider state
// -------------------------------------------------------------------------
/**
* The providers this plugin generates with, as registered by core's
* connector registry, with the state each card starts in:
* not_installed → inactive → needs_key → connected.
*
* Only a key stored in the database counts as connected, because that's
* the only place get_provider_credentials() reads keys from.
*
* @return array[]
*/
private static function get_providers() {
if ( ! function_exists( 'wp_get_connectors' ) ) {
return array();
}
if ( ! function_exists( 'validate_plugin' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$uses = array(
'openai' => __( 'Descriptions, titles, tags and product images', 'ai-content-generator-for-woocommerce' ),
'google' => __( 'Descriptions, titles, tags and product images', 'ai-content-generator-for-woocommerce' ),
'anthropic' => __( 'Descriptions, titles and tags (no image generation)', 'ai-content-generator-for-woocommerce' ),
);
$connectors = wp_get_connectors();
$providers = array();
foreach ( $uses as $id => $use ) {
if ( empty( $connectors[ $id ]['authentication']['setting_name'] ) || empty( $connectors[ $id ]['plugin']['file'] ) ) {
continue;
}
$connector = $connectors[ $id ];
$file = $connector['plugin']['file'];
$setting = $connector['authentication']['setting_name'];
$is_active = ! empty( $connector['plugin']['is_active'] ) && is_callable( $connector['plugin']['is_active'] )
&& call_user_func( $connector['plugin']['is_active'] );
$key = trim( (string) get_option( $setting, '' ) );
if ( ! $is_active ) {
$state = 0 === validate_plugin( $file ) ? 'inactive' : 'not_installed';
} else {
$state = '' !== $key ? 'connected' : 'needs_key';
}
$providers[ $id ] = array(
'id' => $id,
'name' => $connector['name'],
'use' => $use,
'logo_url' => $connector['logo_url'] ?? '',
'keys_url' => $connector['authentication']['credentials_url'] ?? '',
'setting' => $setting,
'slug' => dirname( $file ),
// REST plugin ID: the main file path without ".php".
'plugin' => preg_replace( '/\.php$/', '', $file ),
'state' => $state,
'masked_key' => '' !== $key ? self::mask_key( $key ) : '',
);
}
return $providers;
}
/**
* State of the plugin's own OpenAI key (the "Use Custom ChatGPT API Key" setting).
*
* @return array{connected: bool, masked_key: string}
*/
private static function get_custom_key_state() {
$key = trim( (string) get_option( 'wtofe_chatgpt_api_key', '' ) );
return array(
'connected' => (bool) get_option( 'wtofe_use_custom_api_key', false ) && '' !== $key,
'masked_key' => '' !== $key ? self::mask_key( $key ) : '',
);
}
/**
* Same masking core applies to connector keys in REST responses, so the
* value doesn't change shape when JS swaps in the response after saving.
*
* @param string $key
* @return string
*/
private static function mask_key( $key ) {
if ( strlen( $key ) <= 4 ) {
return $key;
}
return str_repeat( "\u{2022}", min( strlen( $key ) - 4, 16 ) ) . substr( $key, -4 );
}
}