esc_html__('You do not have permission to create templates', 'aitoel-html-importer')));
}
// Check Elementor
if (!HTEL_Elementor_Check::is_active()) {
wp_send_json_error(array('message' => esc_html__('Elementor must be installed and activated', 'aitoel-html-importer')));
}
// Check license — allow free tier (no license) or paid
$has_license = HTEL_License::is_valid_for_conversion();
$license_key = $has_license ? HTEL_License::get_key() : '';
// Get HTML input
$html = '';
$title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : 'Imported Page';
$imported_images = array(); // Track imported image count
if (!empty($_FILES['zip_file']) && isset($_FILES['zip_file']['tmp_name'])) {
// ─── ZIP upload: extract HTML + import images ───
// Build a sanitized copy of the $_FILES entry before passing to
// the handler. Per WP.org review, every $_FILES field read is
// user input and must be sanitized at the boundary.
$zip_file_sanitized = array(
'name' => isset($_FILES['zip_file']['name']) ? sanitize_file_name(wp_unslash($_FILES['zip_file']['name'])) : '',
'tmp_name' => isset($_FILES['zip_file']['tmp_name']) ? sanitize_text_field(wp_unslash($_FILES['zip_file']['tmp_name'])) : '',
'error' => isset($_FILES['zip_file']['error']) ? (int) $_FILES['zip_file']['error'] : UPLOAD_ERR_NO_FILE,
'size' => isset($_FILES['zip_file']['size']) ? (int) $_FILES['zip_file']['size'] : 0,
);
$result = self::handle_zip_upload($zip_file_sanitized, $title);
if (is_wp_error($result)) {
wp_send_json_error(array('message' => $result->get_error_message()));
}
$html = $result['html'];
$title = $result['title'];
$imported_images = $result['imported_images'];
} elseif (!empty($_POST['html_b64'])) {
// Base64-encoded HTML body. The JS encodes the payload before POSTing
// to bypass server-level WAFs (mod_security, Imunify360, BitNinja) on
// shared cPanel hosts that pattern-match request bodies for HTML/script
// signatures and 403 the request before it reaches WordPress. The
// Apache 403 footer is the giveaway — see batch10/SA-customer issue.
//
// Encoding is opaque to WAFs (just base64 chars). Decoding here gets
// us back to the original HTML for the rest of the conversion pipeline,
// identical to the legacy `html` field path below.
//
// wp_unslash because POST data goes through WP's magic-quotes-style
// slash addition; base64_decode is permissive and tolerates the
// expected trailing '=' padding (which doesn't get slash-escaped).
$b64 = wp_unslash($_POST['html_b64']);
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$decoded = base64_decode($b64, true);
if ($decoded === false) {
wp_send_json_error(array('message' => esc_html__('Invalid encoded HTML payload', 'aitoel-html-importer')));
}
$html = $decoded;
} elseif (!empty($_POST['html'])) {
// Legacy plain-text HTML path (kept for backwards compatibility with
// any third-party integrations that POST directly to admin-ajax).
// Note: HTML content is intentionally NOT sanitized with wp_kses() because
// the entire purpose of this plugin is to convert arbitrary HTML to Elementor.
// Sanitizing would strip the HTML structures we need to convert.
// The HTML is sent to our external API for conversion and never rendered
// directly on the site — it is transformed into Elementor JSON data.
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$html = wp_unslash($_POST['html']);
} elseif (!empty($_FILES['html_file']) && isset($_FILES['html_file']['tmp_name'])) {
// Validate file upload structure BEFORE reading any of its fields.
// $_FILES entries are user input and must be sanitized per WP.org
// security review. We:
// - sanitize_file_name() the client-supplied name (never trust it)
// - sanitize_text_field() the tmp_name path before filesystem ops
// - reject anything that isn't the expected structure
$upload_error = isset($_FILES['html_file']['error']) ? (int) $_FILES['html_file']['error'] : UPLOAD_ERR_NO_FILE;
$upload_name = isset($_FILES['html_file']['name']) ? sanitize_file_name(wp_unslash($_FILES['html_file']['name'])) : '';
$upload_tmp = isset($_FILES['html_file']['tmp_name']) ? sanitize_text_field(wp_unslash($_FILES['html_file']['tmp_name'])) : '';
if ($upload_error !== UPLOAD_ERR_OK) {
wp_send_json_error(array('message' => esc_html__('File upload failed', 'aitoel-html-importer')));
}
if (empty($upload_name) || empty($upload_tmp) || !is_uploaded_file($upload_tmp)) {
wp_send_json_error(array('message' => esc_html__('Invalid upload', 'aitoel-html-importer')));
}
$ext = strtolower(pathinfo($upload_name, PATHINFO_EXTENSION));
if ($ext !== 'html' && $ext !== 'htm') {
wp_send_json_error(array('message' => esc_html__('Only .html and .htm files are accepted', 'aitoel-html-importer')));
}
// Use WP_Filesystem if available; fall back to file_get_contents.
// The file lives on the server's tmp dir, validated above.
$html = file_get_contents($upload_tmp);
if ($html === false) {
wp_send_json_error(array('message' => esc_html__('Could not read uploaded file', 'aitoel-html-importer')));
}
if (empty($title) || $title === 'Imported Page') {
// Derive a safe title from the sanitized filename. pathinfo() on
// the already-sanitized $upload_name is safe, and we run the
// result through sanitize_text_field() before sending it to the
// API where it becomes the post_title.
$derived_title = pathinfo($upload_name, PATHINFO_FILENAME);
$title = sanitize_text_field($derived_title);
if (empty($title)) {
$title = 'Imported Page';
}
}
}
if (empty($html)) {
wp_send_json_error(array('message' => esc_html__('No HTML content provided', 'aitoel-html-importer')));
}
// Size check (5MB for HTML content after extraction)
if (strlen($html) > 5 * 1024 * 1024) {
wp_send_json_error(array('message' => esc_html__('HTML exceeds 5MB limit', 'aitoel-html-importer')));
}
// Send to API
$api_url = HTEL_License::get_api_url() . '/api/convert';
$domain = HTEL_License::get_domain();
// Legacy opt-IN telemetry (still honoured for users who previously enabled it)
$telemetry = get_option('htel_telemetry_opt_in', false);
// Conversion Quality Sampling (ToS §9.4) — enabled by default, user can opt OUT.
// We pass the opt-out flag to the API; if true, the API skips sampling.
$sampling_opt_out = get_option('htel_sampling_opt_out', false);
$request_body = array_filter(array(
'html' => $html,
'title' => $title,
'license_key' => $license_key ?: null,
'domain' => $domain,
'telemetry_opt_in' => $telemetry ? true : null,
'sampling_opt_out' => $sampling_opt_out ? true : null,
));
$response = wp_remote_post($api_url, array(
'timeout' => 120, // Allow up to 2 minutes for large pages
'headers' => array('Content-Type' => 'application/json'),
'body' => wp_json_encode($request_body),
));
// Store the HTML in a transient so the "Report a problem" button can retrieve it
set_transient('htel_last_conversion_html', $html, 30 * MINUTE_IN_SECONDS);
if (is_wp_error($response)) {
$err = $response->get_error_message();
$code = $response->get_error_code();
$diag = self::build_connection_error_diagnostic($err, $code, $api_url, strlen(wp_json_encode($request_body)));
wp_send_json_error(array(
'message' => $diag,
'error_code' => $code,
'raw_error' => $err,
));
}
$code = wp_remote_retrieve_response_code($response);
$body = json_decode(wp_remote_retrieve_body($response), true);
if ($code !== 200 || empty($body['success'])) {
$error = isset($body['error']) ? $body['error'] : 'Conversion failed (HTTP ' . $code . ')';
// Free tier service quota reached — neutral error relay (no
// upgrade CTA per WP.org Guideline 5).
if ($error === 'free_limit_reached') {
wp_send_json_error(array(
'message' => isset($body['message']) ? $body['message'] : esc_html__('Conversion service quota reached for this site this month.', 'aitoel-html-importer'),
));
}
// Paid-tier monthly quota reached — relay the API's structured
// usage so the settings page can show "X/Y used this month"
// without an extra round-trip. No upgrade CTA in plugin UI.
if ($error === 'monthly_limit_reached') {
if (isset($body['usage']) && is_array($body['usage'])) {
update_option('htel_license_usage', $body['usage']);
}
wp_send_json_error(array(
'message' => isset($body['message']) ? $body['message'] : esc_html__('Monthly conversion service quota reached.', 'aitoel-html-importer'),
'usage' => isset($body['usage']) ? $body['usage'] : null,
));
}
wp_send_json_error(array('message' => $error));
}
// Persist the live usage counter from the API response so the
// settings page reflects current month's usage without a
// validate round-trip after each conversion.
if (isset($body['usage']) && is_array($body['usage'])) {
update_option('htel_license_usage', $body['usage']);
}
// Save as Elementor template
$template = $body['template'];
$fonts = isset($body['meta']['fonts']) ? $body['meta']['fonts'] : array();
$element_count = isset($body['meta']['element_count']) ? intval($body['meta']['element_count']) : 0;
$template_id = self::save_elementor_template($template, $title, $fonts);
if (is_wp_error($template_id)) {
wp_send_json_error(array(
/* translators: %s: technical error message returned by WordPress */
'message' => sprintf(esc_html__('Failed to save template: %s', 'aitoel-html-importer'), $template_id->get_error_message()),
));
}
$edit_url = admin_url('post.php?post=' . $template_id . '&action=elementor');
$library_url = admin_url('edit.php?post_type=elementor_library');
$success_data = array(
'message' => esc_html__('Template created successfully!', 'aitoel-html-importer'),
'template_id' => $template_id,
'edit_url' => $edit_url,
'library_url' => $library_url,
'element_count' => $element_count,
'font_count' => count($fonts),
'image_count' => count($imported_images),
);
// Per WP.org Guideline 5 (Trialware): the plugin no longer
// forwards free_tier metadata to the JS layer (the metadata was
// previously used to trigger an in-plugin upgrade CTA, which has
// been removed). The external service still enforces quotas;
// when reached they surface via the standard error-message path.
wp_send_json_success($success_data);
}
/**
* Save the converted template as an Elementor library item.
*
* @param array $template The full Elementor template (content, page_settings, etc.)
* @param string $title Template title
* @param array $fonts List of font families used
* @return int|WP_Error Post ID on success, WP_Error on failure
*/
private static function save_elementor_template($template, $title, $fonts) {
// Create the library post
$post_id = wp_insert_post(array(
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'elementor_library',
));
if (is_wp_error($post_id)) {
return $post_id;
}
// Set Elementor data — wp_slash is essential because update_post_meta runs wp_unslash
$elementor_data = wp_json_encode($template['content']);
update_post_meta($post_id, '_elementor_data', wp_slash($elementor_data));
// Set Elementor meta
update_post_meta($post_id, '_elementor_edit_mode', 'builder');
update_post_meta($post_id, '_elementor_template_type', 'page');
update_post_meta($post_id, '_elementor_version', '3.21.0');
// Use Elementor Canvas template — removes theme header/footer/title
// so the converted page renders exactly as designed
update_post_meta($post_id, '_wp_page_template', 'elementor_canvas');
// Set page settings if present
if (!empty($template['page_settings']) && is_array($template['page_settings'])) {
update_post_meta($post_id, '_elementor_page_settings', $template['page_settings']);
}
// Register fonts for Google Fonts loading
$css_meta = array(
'time' => time(),
'fonts' => array_values($fonts),
'icons' => array(),
'dynamic_elements_ids' => array(),
'status' => '',
);
update_post_meta($post_id, '_elementor_css', $css_meta);
// Set template type taxonomy
wp_set_object_terms($post_id, 'page', 'elementor_library_type');
return $post_id;
}
/**
* Handle ZIP file upload: extract HTML file, import images to Media Library,
* replace relative image paths in HTML with WordPress media URLs.
*
* @param array $file $_FILES['zip_file'] data
* @param string $title Template title (may be updated from HTML filename)
* @return array|WP_Error Array with 'html', 'title', 'imported_images' on success
*/
private static function handle_zip_upload($file, $title) {
if ($file['error'] !== UPLOAD_ERR_OK) {
return new WP_Error('upload_error', 'ZIP file upload failed');
}
// Defense-in-depth: ensure this really is a PHP-handled upload and
// the tmp_name wasn't injected via a malicious client. Our caller
// already sanitized the $_FILES fields, but we verify the path is a
// real upload handle before opening it.
if (empty($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
return new WP_Error('upload_error', 'Invalid upload');
}
// 50MB limit for ZIP files
if ($file['size'] > 50 * 1024 * 1024) {
return new WP_Error('too_large', 'ZIP file exceeds 50MB limit');
}
// Name was already sanitized by caller; this is just the extension check.
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if ($ext !== 'zip') {
return new WP_Error('invalid_type', 'Only .zip files are accepted');
}
// Check ZipArchive support
if (!class_exists('ZipArchive')) {
return new WP_Error('no_zip', 'Server does not support ZIP extraction. Please upload an HTML file instead.');
}
$zip = new ZipArchive();
if ($zip->open($file['tmp_name']) !== true) {
return new WP_Error('zip_open', 'Could not open ZIP file');
}
// Find the HTML file and collect image + CSS files
$html_content = '';
$html_filename = '';
$html_dir = ''; // Directory prefix of the HTML file inside the ZIP
$image_entries = array();
$css_entries = array();
$image_extensions = array('jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'ico', 'bmp', 'avif');
for ($i = 0; $i < $zip->numFiles; $i++) {
$entry = $zip->getNameIndex($i);
$basename = basename($entry);
$entry_ext = strtolower(pathinfo($basename, PATHINFO_EXTENSION));
// Skip macOS resource forks and hidden files
if (strpos($entry, '__MACOSX') !== false || strpos($basename, '.') === 0) {
continue;
}
// Block path traversal attacks (e.g., ../../../wp-config.php)
if (strpos($entry, '..') !== false) {
continue;
}
// Find the first HTML file
if (empty($html_filename) && ($entry_ext === 'html' || $entry_ext === 'htm')) {
$html_content = $zip->getFromIndex($i);
$html_filename = $basename;
$html_dir = dirname($entry);
if ($html_dir === '.') {
$html_dir = '';
}
}
// Collect image files
if (in_array($entry_ext, $image_extensions, true)) {
$image_entries[] = array(
'index' => $i,
'path' => $entry, // Full path inside ZIP
'basename' => $basename,
'ext' => $entry_ext,
);
}
// Collect CSS files. We inline these into the HTML before sending
// to the API so the converter sees the full layout — without this,
// any reference
// is dead (the API has no way to fetch relative paths from the
// user's machine), and pages with external stylesheets convert
// missing 50%+ of their CSS (display:grid, flex layouts, etc.).
if ($entry_ext === 'css') {
$css_entries[] = array(
'index' => $i,
'path' => $entry,
'basename' => $basename,
);
}
}
if (empty($html_content)) {
$zip->close();
return new WP_Error('no_html', 'No .html or .htm file found in the ZIP');
}
// Update title from HTML filename if not set
if (empty($title) || $title === 'Imported Page') {
$title = pathinfo($html_filename, PATHINFO_FILENAME);
}
// Import images and build path replacement map
$imported_images = array();
$path_map = array(); // relative_path => wordpress_url
if (!empty($image_entries)) {
// Need these for media uploads
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
foreach ($image_entries as $img) {
$image_data = $zip->getFromIndex($img['index']);
if (empty($image_data)) {
continue;
}
// Write to a temp file for WordPress upload
$tmp_file = wp_tempnam($img['basename']);
file_put_contents($tmp_file, $image_data);
// Determine MIME type
$mime_types = array(
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
'webp' => 'image/webp',
'svg' => 'image/svg+xml',
'ico' => 'image/x-icon',
'bmp' => 'image/bmp',
'avif' => 'image/avif',
);
$mime = isset($mime_types[$img['ext']]) ? $mime_types[$img['ext']] : 'image/jpeg';
// Upload to Media Library
$file_array = array(
'name' => $img['basename'],
'type' => $mime,
'tmp_name' => $tmp_file,
'error' => 0,
'size' => strlen($image_data),
);
$attachment_id = media_handle_sideload($file_array, 0, $img['basename']);
// Clean up temp file if sideload failed. Use wp_delete_file()
// per Plugin Check — it's the WP-blessed wrapper around unlink()
// with filter hooks for extensions/antivirus plugins.
if (is_wp_error($attachment_id)) {
wp_delete_file($tmp_file);
continue;
}
$wp_url = wp_get_attachment_url($attachment_id);
if (!$wp_url) {
continue;
}
$imported_images[] = array(
'original_path' => $img['path'],
'wp_url' => $wp_url,
'attachment_id' => $attachment_id,
);
// Build all possible relative path variations that the HTML might use
$img_path = $img['path'];
// 1. Full path as-is (e.g., "website/assets/photo.jpg")
$path_map[$img_path] = $wp_url;
// 2. Relative to the HTML file's directory
if (!empty($html_dir) && strpos($img_path, $html_dir . '/') === 0) {
$relative = substr($img_path, strlen($html_dir) + 1);
$path_map[$relative] = $wp_url;
$path_map['./' . $relative] = $wp_url;
}
// 3. Just the basename (e.g., "photo.jpg")
$path_map[$img['basename']] = $wp_url;
// 4. Common subfolder patterns (assets/, images/, img/)
$parent_dir = dirname($img_path);
$parent_basename = basename($parent_dir);
if (!empty($parent_basename) && $parent_basename !== '.') {
$path_map[$parent_basename . '/' . $img['basename']] = $wp_url;
$path_map['./' . $parent_basename . '/' . $img['basename']] = $wp_url;
}
}
}
// Sort path_map by length descending so longest matches replace first
// (used by both CSS-content rewrite and HTML-attribute rewrite below).
if (!empty($path_map)) {
uksort($path_map, function($a, $b) {
return strlen($b) - strlen($a);
});
}
// Inline CSS files into the HTML. Two-step:
// (a) Read each CSS, rewrite its url() refs using path_map so
// images sideloaded above are reachable from the inlined CSS.
// (b) Replace each tag in the
// HTML with a block containing the rewritten
// CSS. Skip absolute URLs (Google Fonts, CDNs) — they stay as
// tags so the API/browser can fetch them normally.
$css_lookup = array(); // path-variation => rewritten CSS body
if (!empty($css_entries)) {
foreach ($css_entries as $css) {
$css_content = $zip->getFromIndex($css['index']);
if ($css_content === false || $css_content === '') {
continue;
}
// (a) Rewrite url(...) inside the CSS using image path_map
if (!empty($path_map)) {
foreach ($path_map as $relative_path => $wp_url) {
$escaped = preg_quote($relative_path, '/');
$css_content = preg_replace(
'/(url\s*\(\s*[\'"]?)' . $escaped . '([\'"]?\s*\))/i',
'${1}' . $wp_url . '${2}',
$css_content
);
}
}
// Build all path variations the might use
$css_path = $css['path'];
$variations = array($css_path, $css['basename']);
if (!empty($html_dir) && strpos($css_path, $html_dir . '/') === 0) {
$rel = substr($css_path, strlen($html_dir) + 1);
$variations[] = $rel;
$variations[] = './' . $rel;
}
$parent_basename = basename(dirname($css_path));
if (!empty($parent_basename) && $parent_basename !== '.') {
$variations[] = $parent_basename . '/' . $css['basename'];
$variations[] = './' . $parent_basename . '/' . $css['basename'];
}
foreach (array_unique($variations) as $var) {
$css_lookup[$var] = $css_content;
}
}
}
$zip->close();
// (b) Replace with
// for any href whose path matches an extracted CSS file.
if (!empty($css_lookup)) {
$html_content = preg_replace_callback(
'/]*>/i',
function ($m) use ($css_lookup) {
$tag = $m[0];
// Must be rel="stylesheet" (skip preload, prefetch, icon, etc.)
if (!preg_match('/\brel\s*=\s*["\']?stylesheet["\']?/i', $tag)) {
return $tag;
}
// Extract href
if (!preg_match('/\bhref\s*=\s*["\']([^"\']+)["\']/i', $tag, $h)) {
return $tag;
}
$href = $h[1];
// Skip absolute URLs (Google Fonts, CDNs, etc.) — they can
// be fetched normally and shouldn't be inlined.
if (preg_match('#^(https?:)?//#i', $href)) {
return $tag;
}
// Try the href as-is and with leading "./" stripped
$candidates = array($href, ltrim($href, './'));
foreach ($candidates as $c) {
if (isset($css_lookup[$c])) {
return "";
}
}
return $tag;
},
$html_content
);
}
// Replace relative image paths in HTML with WordPress URLs
if (!empty($path_map)) {
foreach ($path_map as $relative_path => $wp_url) {
// Replace in src="...", url('...'), url("..."), and url(...)
$escaped = preg_quote($relative_path, '/');
// src="path" and href="path" and poster="path"
$html_content = preg_replace(
'/((?:src|href|poster|data-src|data-bg)\s*=\s*["\'])' . $escaped . '(["\'])/i',
'${1}' . $wp_url . '${2}',
$html_content
);
// url('path'), url("path"), url(path) in CSS
$html_content = preg_replace(
'/(url\s*\(\s*[\'"]?)' . $escaped . '([\'"]?\s*\))/i',
'${1}' . $wp_url . '${2}',
$html_content
);
}
}
return array(
'html' => $html_content,
'title' => $title,
'imported_images' => $imported_images,
);
}
/**
* AJAX handler for feedback reports ("Report a problem" button).
*/
public static function ajax_feedback() {
check_ajax_referer('htel_convert_nonce', 'nonce');
if (!current_user_can('edit_posts')) {
wp_send_json_error(array('message' => esc_html__('Permission denied', 'aitoel-html-importer')));
}
$description = isset($_POST['description']) ? sanitize_textarea_field(wp_unslash($_POST['description'])) : '';
if (empty($description)) {
wp_send_json_error(array('message' => esc_html__('Please describe the problem', 'aitoel-html-importer')));
}
// Retrieve the HTML from the transient (stored during conversion)
$html = get_transient('htel_last_conversion_html');
if (empty($html)) {
wp_send_json_error(array('message' => esc_html__('No recent conversion found. Please convert a page first, then report.', 'aitoel-html-importer')));
}
$api_url = HTEL_License::get_api_url() . '/api/feedback';
$domain = HTEL_License::get_domain();
$response = wp_remote_post($api_url, array(
'timeout' => 30,
'headers' => array('Content-Type' => 'application/json'),
'body' => wp_json_encode(array(
'html' => $html,
'description' => $description,
'domain' => $domain,
)),
));
if (is_wp_error($response)) {
wp_send_json_error(array(
/* translators: %s: technical error message from WordPress HTTP API */
'message' => sprintf(esc_html__('Could not send feedback: %s', 'aitoel-html-importer'), $response->get_error_message()),
));
}
$body = json_decode(wp_remote_retrieve_body($response), true);
if (empty($body['success'])) {
wp_send_json_error(array('message' => isset($body['error']) ? $body['error'] : esc_html__('Failed to send feedback', 'aitoel-html-importer')));
}
// Clear the transient after successful report
delete_transient('htel_last_conversion_html');
wp_send_json_success(array('message' => esc_html__('Thank you! Your feedback helps us improve the converter.', 'aitoel-html-importer')));
}
/**
* Build a diagnostic error message for connection failures.
*
* The default WordPress error message for blocked outbound HTTP is
* misleading: "A valid URL was not provided" actually means a security
* plugin's `pre_http_request` filter rejected the request, not that the
* URL is malformed. We do three things to produce actionable diagnostics:
*
* 1. Run a tiny GET against /api/health from the SAME WordPress install.
* If that succeeds (200), the convert request specifically failed —
* points at body-size or timeout-based filters (SG Security typical).
* If that also fails, outbound HTTPS is fully blocked.
*
* 2. Detect known security/optimisation plugins that intercept HTTP
* (SG Security, LiteSpeed Cache, Wordfence, iThemes Security, Solid
* Security, MalCare). Mention the active one by name with targeted
* fix steps.
*
* 3. Mention WP_HTTP_BLOCK_EXTERNAL constant if defined.
*/
private static function build_connection_error_diagnostic($err, $code, $api_url, $request_body_size) {
// Probe 0: is the API URL the customer is sending to actually well-formed?
// The v1.3.14 customer bug: a stored htel_api_url option of '' produces a
// bare-path URL that wp_remote_post rejects with "A valid URL was not provided"
// / "Non è stato fornito un URL valido". The old diagnostic blamed the
// firewall (because /api/health probe ALSO uses the broken URL → also fails
// → "fully blocked"). Now we check the URL itself first.
$url_is_malformed = empty($api_url)
|| !is_string($api_url)
|| !preg_match('#^https?://[^\s/]+#i', $api_url)
|| !filter_var($api_url, FILTER_VALIDATE_URL);
// Cross-check the error message: WP returns the same code (http_request_failed)
// for both invalid URL and outbound block, but distinct error text.
$err_text = is_string($err) ? strtolower($err) : '';
$err_indicates_invalid_url = strpos($err_text, 'valid url') !== false
|| strpos($err_text, 'url valid') !== false // Italian: "URL valido"
|| strpos($err_text, 'url valide') !== false // French: "URL valide"
|| strpos($err_text, 'gültig') !== false // German: "gültig"
|| strpos($err_text, 'no se proporcion') !== false; // Spanish
if ($url_is_malformed || $err_indicates_invalid_url) {
$diag = "Could not connect to conversion service.\n\n";
$diag .= "Technical error: " . $err . " (code: " . $code . ")\n";
$diag .= "Configured API URL: " . ($api_url === '' ? '(empty)' : $api_url) . "\n\n";
$diag .= "DIAGNOSIS: the API URL stored in your plugin settings is empty or\n";
$diag .= " malformed. WordPress rejected the conversion request because the\n";
$diag .= " URL has no scheme/host. THIS IS NOT A FIREWALL OR SECURITY ISSUE.\n\n";
$diag .= "FIX (1 minute, no plugin update needed):\n";
$diag .= " 1. WordPress admin → AI to Elementor → Settings\n";
$diag .= " 2. Find the \"API URL\" field\n";
$diag .= " 3. Set it to: " . HTEL_API_URL . "\n";
$diag .= " 4. Save Changes\n";
$diag .= " 5. Retry the conversion — it will work.\n\n";
$diag .= "Plugin v1.3.15+ auto-corrects this: invalid URL is detected and the\n";
$diag .= "default is used automatically. Update the plugin to avoid this in future.\n\n";
$diag .= "Still stuck? Email support@aitoelementor.com with this entire message.";
return $diag;
}
// Probe 1: tiny GET against /api/health to see if outbound HTTPS works at all
$health_url = HTEL_License::get_api_url() . '/api/health';
$health = wp_remote_get($health_url, array('timeout' => 8));
$health_works = !is_wp_error($health) && wp_remote_retrieve_response_code($health) === 200;
// Probe 2: detect known security/optimisation plugins that filter HTTP
$known_filters = array(
'sg-security/sg-security.php' => array('SG Security', 'Site Tools → Security → Outgoing Connections — add api.aitoelementor.com to the allowlist'),
'sg-security/index.php' => array('SG Security', 'Site Tools → Security → Outgoing Connections — add api.aitoelementor.com to the allowlist'),
'sg-cachepress/sg-cachepress.php' => array('SG Optimizer', 'SG Optimizer → Misc → Disable "Block requests to external resources" or whitelist api.aitoelementor.com'),
'litespeed-cache/litespeed-cache.php' => array('LiteSpeed Cache', 'LiteSpeed Cache → Toolbox → Heartbeat → disable Heartbeat throttling, OR temporarily deactivate the plugin during conversion'),
'wordfence/wordfence.php' => array('Wordfence', 'Wordfence → Firewall → All Firewall Options → Allowlisted URLs — add /wp-admin/admin-ajax.php with parameter "html"'),
'better-wp-security/better-wp-security.php' => array('iThemes Security', 'iThemes Security → Settings → Security Check — pause; OR Solid Security → Lockouts → exempt your IP'),
'ithemes-security-pro/ithemes-security-pro.php' => array('iThemes Security Pro','iThemes Security → Settings — disable "Block tabnabbing" / "Limit external requests"'),
'solid-security/solid-security.php' => array('Solid Security', 'Solid Security → Settings → exempt api.aitoelementor.com from outbound restrictions'),
'solid-security-pro/solid-security-pro.php' => array('Solid Security Pro', 'Solid Security → Settings → exempt api.aitoelementor.com'),
'malcare-security/malcare.php' => array('MalCare', 'MalCare → Site Settings — disable Auto-Block during conversion'),
'wpvivid-backuprestore/wpvivid-backuprestore.php'=> array('WPvivid', '(unlikely culprit, but bundles HTTP filters — try deactivating during conversion)'),
);
$detected = array();
if (function_exists('get_option')) {
$active = get_option('active_plugins', array());
// Multisite: also network-active
if (function_exists('get_site_option')) {
$network = get_site_option('active_sitewide_plugins', array());
if (is_array($network)) $active = array_merge($active, array_keys($network));
}
foreach ($known_filters as $slug => $info) {
if (in_array($slug, $active, true)) $detected[] = $info;
}
}
$diag = "Could not connect to conversion service.\n\n";
$diag .= "Technical error: " . $err . " (code: " . $code . ")\n";
$diag .= "Request body size: " . round($request_body_size / 1024, 1) . " KB\n\n";
// Most actionable diagnosis first
if ($health_works) {
$diag .= "DIAGNOSIS: outbound HTTPS to api.aitoelementor.com IS working — a small\n";
$diag .= " /api/health request just succeeded from your server. The conversion\n";
$diag .= " request specifically is being blocked, almost certainly by a security\n";
$diag .= " plugin's request-body filter (large payload, longer timeout).\n\n";
} else {
$diag .= "DIAGNOSIS: outbound HTTPS to api.aitoelementor.com is fully blocked\n";
$diag .= " on your server. Even a tiny /api/health request fails.\n\n";
}
if (!empty($detected)) {
$diag .= "DETECTED SECURITY PLUGIN" . (count($detected) > 1 ? "S" : "") . ":\n";
foreach ($detected as $info) {
list($name, $fix) = $info;
$diag .= " • {$name}\n Fix: {$fix}\n";
}
$diag .= "\n";
}
$diag .= "Other things to try:\n";
$diag .= " • Add to wp-config.php (if not present):\n";
$diag .= " define('WP_ACCESSIBLE_HOSTS', 'api.aitoelementor.com,*.aitoelementor.com');\n";
if (defined('WP_HTTP_BLOCK_EXTERNAL') && WP_HTTP_BLOCK_EXTERNAL) {
$diag .= " • WP_HTTP_BLOCK_EXTERNAL is currently TRUE in wp-config.php — the\n";
$diag .= " WP_ACCESSIBLE_HOSTS allowlist above is required for our API to be reached.\n";
}
$diag .= " • If you're on managed hosting, ask support to whitelist api.aitoelementor.com (port 443)\n";
$diag .= " • Temporarily deactivate any security/firewall plugin and retry\n\n";
$diag .= "Still stuck? Email support@aitoelementor.com with this entire message.";
return $diag;
}
}