"ehdi_sanitize_api_key"] ); register_setting( "ehdi_settings_group", "ehdi_selected_company_id", ["sanitize_callback" => "ehdi_sanitize_company_id"] ); register_setting("ehdi_settings_group", "ehdi_dni_script", [ "sanitize_callback" => "ehdi_sanitize_dni_script" ]); register_setting("ehdi_settings_group", "ehdi_wrap_script", [ "default" => 0, "sanitize_callback" => "ehdi_sanitize_wrap_script" ]); // API Section add_settings_section( "ehdi_api_section", "API Configuration", "ehdi_api_section_callback", "eight_hundred_dni_injector" ); add_settings_field( "ehdi_api_key_field", "800.com API Key", "ehdi_api_key_field_render", "eight_hundred_dni_injector", "ehdi_api_section" ); // Company Selection Section add_settings_section( "ehdi_company_section", "Company Selection", "ehdi_company_section_callback", "eight_hundred_dni_injector" ); add_settings_field( "ehdi_company_select_field", "Select Company", "ehdi_company_select_field_render", "eight_hundred_dni_injector", "ehdi_company_section" ); // DNI Script Display Section add_settings_section( "ehdi_script_display_section", "Fetched DNI Script", "ehdi_script_display_section_callback", "eight_hundred_dni_injector" ); add_settings_field( "ehdi_script_display_field", "Current DNI Script", "ehdi_script_display_field_render", "eight_hundred_dni_injector", "ehdi_script_display_section" ); add_settings_field( "ehdi_wrap_script_field", "Script Injection Method", "ehdi_wrap_script_field_render", "eight_hundred_dni_injector", "ehdi_script_display_section" ); } add_action('admin_init', 'ehdi_settings_init'); /** * Callback for API section. */ function ehdi_api_section_callback() { ?>

Enter your 800.com API key below obtained from your Integrations page inside of 800.com. This will be used to configure DNI

Please enter and save your API key above to fetch and select a company.

'); } else { echo wp_kses_post('

Select the company for which you want to inject the DNI script.

'); // Company list will be populated here via another function later } } /** * Render Company Select field. * Fetches companies if API key is available and populates dropdown. */ function ehdi_company_select_field_render() { $api_key = get_option("ehdi_api_key"); $selected_company_id = get_option("ehdi_selected_company_id"); if (empty($api_key)) { echo '

' . esc_html("API Key not set. Cannot fetch companies.") . '

'; return; } $companies_result = ehdi_fetch_companies($api_key); if (is_wp_error($companies_result)) { echo '

' . esc_html("Error fetching companies:") . ' ' . esc_html($companies_result->get_error_message()) . '

'; // Still show the currently selected ID if one exists if ($selected_company_id) { echo '

' . esc_html("Currently saved company ID:") . ' ' . esc_html($selected_company_id) . '

'; // Provide a hidden input so the value isn't lost on save if API fails temporarily echo ''; } return; } if (empty($companies_result)) { echo '

' . esc_html("No companies found or API response was empty.") . '

'; return; } // We have companies, render the select dropdown ?>

[ "Authorization" => "Bearer " . $api_key, // Assuming no specific Accept header is needed for raw script, but can add if required ], "timeout" => 15, // Set a reasonable timeout ]; $response = wp_remote_get($url, $args); if (is_wp_error($response)) { return $response; // Return the WP_Error object } $response_code = wp_remote_retrieve_response_code($response); $response_body = wp_remote_retrieve_body($response); if ($response_code !== 200) { $error_message = sprintf("DNI Script API request failed (%s) with status code %d.", $url, $response_code); // Attempt to decode JSON error message, though it might be plain text $body_data = json_decode($response_body, true); if ($body_data) { $error_message .= " " . esc_html($body_data["message"]); } elseif (!empty($response_body)) { $error_message .= " Response: " . esc_html(substr($response_body, 0, 100)); // Show start of response } return new WP_Error("dni_api_request_failed", $error_message); } $body_data = json_decode($response_body, true); if (json_last_error() !== JSON_ERROR_NONE) { return new WP_Error("json_decode_failed", "Failed to decode API response."); } if (!isset($body_data["data"])) { return new WP_Error("script_not_found", "DNI script not found in API response."); } return $body_data["data"]; // Assuming the script is in 'data' key } /** * Action triggered on PHP shutdown. * This is a fallback for the transient-based admin notices. */ function ehdi_fetch_script_on_shutdown() { // This function is kept for backward compatibility // The actual fetching is now done in ehdi_handle_company_update_filter } add_action("shutdown", "ehdi_fetch_script_on_shutdown"); /** * Display admin notices based on the transient. */ function ehdi_display_admin_notices() { if ($notice = get_transient("ehdi_admin_notice")) { $type = isset($notice["type"]) ? $notice["type"] : "info"; // Default to info $message = isset($notice["message"]) ? $notice["message"] : ""; if (!empty($message)) { printf( '

%s

', esc_attr($type), wp_kses_post($message) // Use wp_kses_post for safety if message contains HTML ); // Delete the transient so it doesn't show again on refresh delete_transient("ehdi_admin_notice"); } } } add_action("admin_notices", "ehdi_display_admin_notices"); // Append the fetch companies function as well /** * Fetch companies from 800.com API. * * @param string $api_key The API key. * @return array|WP_Error Array of companies on success, WP_Error on failure. */ function ehdi_fetch_companies($api_key) { if (empty($api_key)) { return new WP_Error("api_key_missing", "API Key is not provided."); } $base_url = EHDI_API_BASE_URL; // Ensure base URL doesn't have a trailing slash and append the specific endpoint $url = rtrim($base_url, "/") . "/companies/slim?query=&page=1&per_page=100"; $args = [ "headers" => [ "Authorization" => "Bearer " . $api_key, "Accept" => "application/json", ], "timeout" => 15, // Set a reasonable timeout ]; $response = wp_remote_get($url, $args); if (is_wp_error($response)) { return $response; // Return the WP_Error object } $response_code = wp_remote_retrieve_response_code($response); $response_body = wp_remote_retrieve_body($response); if ($response_code !== 200) { // Try to get more info from the body if possible $error_message = sprintf("API request failed (%s) with status code %d.", $url, $response_code); $body_data = json_decode($response_body, true); if ($body_data && isset($body_data["message"])) { $error_message .= " " . esc_html($body_data["message"]); } return new WP_Error("api_request_failed", $error_message); } $companies_data = json_decode($response_body, true); if (json_last_error() !== JSON_ERROR_NONE) { return new WP_Error("json_decode_failed", "Failed to decode API response."); } // Adjust this based on the actual API response structure if (!isset($companies_data["data"]) || !is_array($companies_data["data"])) { if (is_array($companies_data) && !empty($companies_data) && isset($companies_data[0]["id"])) { return $companies_data; } if (isset($companies_data["data"]) && is_array($companies_data["data"])) { return $companies_data["data"]; } return new WP_Error("invalid_response_structure", "Unexpected API response structure."); } return $companies_data["data"]; } // Frontend Script Injection /** * Enqueue DNI script using WordPress proper methods. */ function ehdi_enqueue_dni_script() { $dni_script = get_option("ehdi_dni_script"); $wrap_script = get_option("ehdi_wrap_script"); if (!empty($dni_script)) { if ($wrap_script) { // Register a dummy script handle for our inline script wp_register_script( 'ehdi-dni-wrapper', // Unique handle for our script false, // No external file array(), // No dependencies needed EHDI_PLUGIN_VERSION, // Use plugin version true // Load in footer ); wp_enqueue_script('ehdi-dni-wrapper'); // Create a dynamic wrapper script that bypasses optimization $wrapper_script = ' (function() { // Wait for DOM to be ready function injectScript() { var scriptContent = ' . wp_json_encode($dni_script) . '; var srcMatch = scriptContent.match(/src=[\'"]([^\'"]+)[\'"]/) || []; var scriptSrc = srcMatch[1] || ""; if (scriptSrc) { var script = document.createElement("script"); script.src = scriptSrc; script.type = "text/javascript"; // Extract and copy any other attributes from the original script var attrMatch; var attrRegex = /(\w+)=[\'"]([^\'"]+)[\'"](?:\s|>)/g; while ((attrMatch = attrRegex.exec(scriptContent)) !== null) { var attrName = attrMatch[1]; var attrValue = attrMatch[2]; if (attrName !== "src" && attrName !== "type") { script.setAttribute(attrName, attrValue); } } document.head.appendChild(script); } } // Execute immediately or when DOM is ready if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", injectScript); } else { injectScript(); } })();'; // Add the inline script, tied to our dummy handle wp_add_inline_script('ehdi-dni-wrapper', $wrapper_script); } } } add_action('wp_enqueue_scripts', 'ehdi_enqueue_dni_script'); /** * Output DNI script directly in footer for non-wrapped mode. */ function ehdi_output_dni_script_direct() { $dni_script = get_option("ehdi_dni_script"); $wrap_script = get_option("ehdi_wrap_script"); // Only output directly if wrap_script is disabled if (!empty($dni_script) && !$wrap_script) { echo "\n\n"; // Output the script directly, but safely escaped echo wp_kses($dni_script, array( 'script' => array( 'type' => array(), 'src' => array(), 'async' => array(), 'defer' => array(), 'id' => array(), 'class' => array(), 'data-*' => array() ) )); echo "\n\n"; } } add_action('wp_footer', 'ehdi_output_dni_script_direct', 999); /** * Add DNI Script Display section. */ function ehdi_script_display_section_callback() { echo wp_kses_post("

The following DNI script has been fetched based on your selected company and will be injected into the <head> section of all frontend pages.

"); } /** * Render the DNI Script display field. */ function ehdi_script_display_field_render() { $dni_script = get_option("ehdi_dni_script"); $has_script = !empty($dni_script); echo '

Current DNI Script:

'; // Add error display area (separate from textarea) echo ''; // Add a textarea for the actual form input with smaller, more reasonable sizing $rows = $has_script ? '6' : '3'; $placeholder = $has_script ? '' : 'No script loaded. Select a company above to fetch the DNI script.'; echo ''; // Add description echo '

' . esc_html('This script is automatically fetched when you select a company above. It will be injected into your website pages.') . '

'; // Add spinner for auto-refresh functionality echo '

'; echo '
'; // Close wrapper div } /** * Render the Script Wrapping checkbox field. */ function ehdi_wrap_script_field_render() { $wrap_script = get_option('ehdi_wrap_script'); ?>

array( 'type' => array(), 'src' => array(), 'async' => array(), 'defer' => array(), 'id' => array(), 'class' => array(), 'data-*' => true, // Allow data attributes 'crossorigin' => array(), 'integrity' => array(), 'nonce' => array(), ) ); return wp_kses($input, $allowed_html); } /** * Sanitize callback for wrap script option. * * @param mixed $input The value submitted via the form. * @return int The sanitized wrap script value. */ function ehdi_sanitize_wrap_script($input) { return absint($input); } /** * Enqueue admin scripts for the settings page. */ /** * Enqueue admin scripts for the settings page. * * Note: This function uses $_GET['page'] for script enqueueing only, not for processing form data * that changes anything on the server, so nonce verification is not required here. */ function ehdi_enqueue_admin_scripts($hook_suffix) { // Only load on our specific settings page if ($hook_suffix === 'settings_page_eight_hundred_dni_injector') { // We're on the settings page, enqueue scripts } else { // Check if we're on the options.php page after saving settings $screen = get_current_screen(); if ($screen && $screen->id === 'options') { // We might be on options.php after saving our plugin settings // Get the page parameter safely $page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS); if ($page !== 'eight_hundred_dni_injector') { return; } } else { return; } } wp_enqueue_script( 'ehdi-admin-script', plugin_dir_url(__FILE__) . 'admin-script.js', ['jquery'], // Dependency EHDI_PLUGIN_VERSION, // Use defined version true // Load in footer ); // Localize script to pass data like nonce and ajax url wp_localize_script('ehdi-admin-script', 'ehdi_ajax_object', [ 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('ehdi_refresh_script_nonce'), 'loading_text' => 'Loading...', 'error_text' => 'Error fetching script.', 'no_company_text' => 'Please select a company first.', ]); // Enqueue admin styles wp_enqueue_style( 'ehdi-admin-style', plugin_dir_url(__FILE__) . 'admin-style.css', [], // No dependencies EHDI_PLUGIN_VERSION // Use defined version ); } add_action('admin_enqueue_scripts', 'ehdi_enqueue_admin_scripts'); /** * AJAX handler for refreshing the DNI script. */ function ehdi_ajax_refresh_script_handler() { // Verify nonce check_ajax_referer('ehdi_refresh_script_nonce', 'nonce'); // Check user capabilities if (!current_user_can('manage_options')) { wp_send_json_error(['message' => 'Permission denied.'], 403); } // Get API key $api_key = get_option('ehdi_api_key'); // Get company ID from request if provided, otherwise use the saved one $company_id = isset($_POST['company_id']) && !empty($_POST['company_id']) ? sanitize_text_field(wp_unslash($_POST['company_id'])) : get_option('ehdi_selected_company_id'); if (empty($company_id)) { wp_send_json_error(['message' => 'No company selected. Please select a company from the dropdown.'], 400); } if (empty($api_key)) { wp_send_json_error(['message' => 'API Key is missing.'], 400); } // Fetch the script $script_result = ehdi_fetch_dni_script($company_id, $api_key); if (is_wp_error($script_result)) { wp_send_json_error(['message' => $script_result->get_error_message()], 500); } else { // Force the script to be a string if it's not already if (!is_string($script_result)) { $script_result = (string)$script_result; } // Send success response with the script content for preview only // Do not save to database - that will happen when user clicks "Save Settings" wp_send_json_success(['script' => $script_result]); } } add_action('wp_ajax_ehdi_refresh_script', 'ehdi_ajax_refresh_script_handler'); ?>