]*>(.*?)<\/\1>/is', $content); if ($containsHtml) { $tags = []; $content = preg_replace_callback('/<([a-z][a-z0-9]*)\b[^>]*>(.*?)<\/\1>/is', function($matches) use (&$tags) { $placeholder = '##HTML_TAG_' . count($tags) . '##'; $tags[$placeholder] = $matches[0]; return $placeholder; }, $content); } $content = self::formatVariables($content); $direct_replacements = [ '"\\u2013"' => '"-"', '"\\u2019"' => '"\'', '\\u2013' => '-', '\\u2019' => '\'', '\u2013' => '-', '\u2019' => '\'', "\\u2013" => "-", "\\u2019" => "'" ]; foreach ($direct_replacements as $search => $replace) { $content = str_replace($search, $replace, $content); } $content = preg_replace_callback('/(?:\\\\u|\\\\\\\\u)([0-9a-fA-F]{4})/', function($matches) { return html_entity_decode('&#x' . $matches[1] . ';', ENT_QUOTES, 'UTF-8'); }, $content); $specialChars = [ '\u2019' => "'", '\u2018' => "'", '\u201C' => '"', '\u201D' => '"', '\u2013' => '-', '\u2014' => '--', '\u00A0' => ' ', '\u00AD' => '-', '\u2026' => '...', ]; foreach ($specialChars as $unicodeChar => $replacement) { $content = str_replace($unicodeChar, $replacement, $content); } $content = preg_replace('/[-\*]?\s*(Attributes|Categories|Tags|Price):\s*$/m', '', $content); $content = preg_replace('/[-\*]?\s*(Attributes|Categories|Tags|Price):\s*\n/m', '', $content); if ($repairMarkdown) { $content = preg_replace('/\*\*(.+?)\*\*/s', '$1', $content); $content = preg_replace('/\*(?!\s)([^*\n]+?)(? '-', '\u2019' => "'", '\\u2013' => '-', '\\u2019' => "'" ]; foreach ($final_replacements as $search => $replace) { $content = str_replace($search, $replace, $content); } if ($containsHtml && !empty($tags)) { foreach ($tags as $placeholder => $originalTag) { $content = str_replace($placeholder, $originalTag, $content); } } return trim($content); } /** * Değişkenleri formatlayarak ön ekler ekleyen fonksiyon * * Örnek: {PRICE} değişkenini Price: {PRICE} şeklinde formatlar. * Eğer değişken boş ise hiçbir ön ek eklemez. * * @param string $content Formatlama yapılacak içerik * @param array $replacements Değişkenlerin gerçek değerlerini içeren assoc array (opsiyonel) * @return string Değişkenleri formatlanmış içerik */ public static function formatVariables(string $content, array $replacements = []): string { preg_match_all('/{([A-Za-z0-9_]+)}/', $content, $matches); if (empty($matches[0])) { return $content; } foreach ($matches[0] as $index => $fullMatch) { $variableName = $matches[1][$index]; $variableValue = ""; if (isset($replacements[$fullMatch])) { $variableValue = $replacements[$fullMatch]; } else { $variableValue = $fullMatch; } if (empty($variableValue) || $variableValue === $fullMatch) { continue; } $systemVariables = ['max_length', 'max_short_length', 'language', 'style', 'title']; if (in_array(strtolower($variableName), $systemVariables, true)) { $content = str_replace($fullMatch, $variableValue, $content); continue; } $formattedName = implode(' ', array_map('ucfirst', array_map('strtolower', explode('_', $variableName)))); $replacement = $formattedName . ': ' . $variableValue; $content = str_replace($fullMatch, $replacement, $content); } return $content; } /** * AI'dan gelen metni WordPress editörü için düzgün formatlama * * @param string $text AI'dan gelen ham metin * @return string WordPress editörü için formatlanmış metin */ public static function formatAiResponseForWordPress($text) { $text = preg_replace('/^\s*```[a-zA-Z]*\s*\n/', '', $text); $text = preg_replace('/\n\s*```\s*$/', '', $text); $trimmed = ltrim( $text ); if ( '' !== $trimmed && '<' === $trimmed[0] && preg_match( '/^<[a-zA-Z][a-zA-Z0-9]*\b/', $trimmed ) ) { $first_gt = strpos( $trimmed, '>', 0 ); $first_lt = strpos( $trimmed, '<', 1 ); if ( false === $first_gt || ( false !== $first_lt && $first_lt < $first_gt ) ) { $text = ltrim( $text ); $text = substr( $text, 1 ); } } $hasHtml = preg_match('/<[a-zA-Z][^>]*>/', $text); if ($hasHtml) { return wp_kses_post($text); } $lines = explode("\n", $text); $in_list = false; $list_type = ''; $formatted_lines = []; foreach ($lines as $line) { $line = preg_replace('/```[a-zA-Z]*/', '', $line); $line = preg_replace('/```/', '', $line); $trimmed = trim($line); if (!empty($trimmed)) { $trimmed = sanitize_text_field($trimmed); if (preg_match('/^(#+)\s+(.+)$/', $trimmed, $matches)) { $headerLevel = strlen($matches[1]); if ($headerLevel >= 1 && $headerLevel <= 3) { if ($in_list) { $in_list = false; $formatted_lines[] = $list_type === 'ul' ? '' : ''; $list_type = ''; } $formatted_lines[] = '' . self::formatInlineMarkdown(esc_html($matches[2])) . ''; continue; } } if (preg_match('/^(-|\*)\s+(.+)$/', $trimmed, $matches)) { if (!$in_list || $list_type !== 'ul') { if ($in_list && $list_type === 'ol') { $formatted_lines[] = ''; } $in_list = true; $list_type = 'ul'; $formatted_lines[] = ''; } $in_list = true; $list_type = 'ol'; $formatted_lines[] = '
    '; } $formatted_lines[] = '
  1. ' . self::formatInlineMarkdown(esc_html($matches[2])) . '
  2. '; } else { if ($in_list) { $in_list = false; $formatted_lines[] = $list_type === 'ul' ? '' : '
'; $list_type = ''; } if (preg_match('/^([A-Za-z0-9\s]+):$/', $trimmed, $matches)) { $formatted_lines[] = '

' . esc_html($matches[1]) . '

'; } else { $formatted_lines[] = '

' . self::formatInlineMarkdown(esc_html($trimmed)) . '

'; } } } elseif (empty($trimmed) && !empty($line)) { $formatted_lines[] = '
'; } } if ($in_list) { $formatted_lines[] = $list_type === 'ul' ? '' : ''; } return wp_kses_post(implode("\n", $formatted_lines)); } /** * Convert inline Markdown emphasis in already escaped text. * * @param string $escaped Escaped line text. * @return string Text with / tags. */ private static function formatInlineMarkdown($escaped) { $escaped = preg_replace('/\*\*\*(.+?)\*\*\*/', '$1', $escaped); $escaped = preg_replace('/\*\*(.+?)\*\*/', '$1', $escaped); return preg_replace('/\*(?!\s)(.+?)(?$1', $escaped); } /** * Replace stored custom variable tokens with their product values. * * Tokens are matched by their exact stored name ({material}), the form the * prompt editors insert, and replaced with the raw value, as the bulk * description prompt does. Tokens without a non-empty value are left as * written. * * Every name that `CustomFields::sanitize_custom_variable()` can persist * must be substitutable here. That validation accepts any non-empty name * up to 100 characters without braces, angle brackets or control * characters, so spaced ("care instructions"), hyphenated and non-ASCII * names are all legal and are stored with the matching `{name}` * placeholder. Only braces are rejected below, because a name containing * one would make the `{name}` token boundary ambiguous; a numeric name is * accepted as the integer array key PHP converts it to. Anything else * would silently leave the literal placeholder in the provider prompt. * * @param string $content Prompt text. * @param array $custom_variables Variable name => value (ProductDataFormatter / ProductDataProvider shape). * @return string */ public static function replaceCustomVariables(string $content, array $custom_variables): string { $map = []; foreach ($custom_variables as $name => $value) { if (!is_string($name) && !is_int($name)) { continue; } $name = (string) $name; if ('' === $name || false !== strpbrk($name, '{}')) { continue; } $string_value = VariableConverter::toString($value); if ('' === $string_value) { continue; } $map['{' . $name . '}'] = $string_value; } return empty($map) ? $content : strtr($content, $map); } /** * Ürün değişkenlerini gerçek değerleriyle değiştiren ve uygun formatta sunan fonksiyon * * @param string $content Formatlama yapılacak içerik * @param array $productData Ürün verilerini içeren dizi * @return string Formatlanmış içerik */ public static function formatProductVariables(string $content, array $productData): string { $replacements = []; $currency = isset($productData['currency']) ? $productData['currency'] : get_woocommerce_currency(); $possibleVariables = [ '{NAME}' => $productData['name'] ?? '', '{SHORT_DESCRIPTION}' => $productData['short_description'] ?? '', '{LONG_DESCRIPTION}' => $productData['long_description'] ?? $productData['description'] ?? '', '{PRICE}' => isset($productData['price']) && !empty($productData['price']) ? $productData['price'] . " " . $currency : '', '{REGULAR_PRICE}' => isset($productData['regular_price']) && !empty($productData['regular_price']) ? $productData['regular_price'] . " " . $currency : '', '{SALE_PRICE}' => isset($productData['sale_price']) && !empty($productData['sale_price']) ? $productData['sale_price'] . " " . $currency : '', '{CATEGORIES}' => $productData['categories'] ?? '', '{TAGS}' => $productData['tags'] ?? '', '{SKU}' => $productData['sku'] ?? '', '{ATTRIBUTES}' => $productData['attributes'] ?? '', ]; $safeVariables = VariableConverter::convertVariables($possibleVariables); foreach ($safeVariables as $placeholder => $value) { if (!empty($value)) { $replacements[$placeholder] = $value; } } if (isset($productData['attributes']) && is_array($productData['attributes'])) { foreach ($productData['attributes'] as $attrName => $attrValue) { $safeValue = VariableConverter::toString($attrValue); if (!empty($safeValue)) { $placeholder = '{' . strtoupper($attrName) . '}'; $replacements[$placeholder] = $safeValue; } } } $formattedContent = self::formatVariables($content, $replacements); if (isset($productData['custom_variables']) && is_array($productData['custom_variables'])) { $formattedContent = self::replaceCustomVariables($formattedContent, $productData['custom_variables']); } preg_match_all('/{([A-Z0-9_]+)}/', $formattedContent, $remainingMatches); if (!empty($remainingMatches[0])) { foreach ($remainingMatches[0] as $placeholder) { $formattedContent = preg_replace('/^\s*' . preg_quote($placeholder, '/') . '\s*$/m', '', $formattedContent); $formattedContent = preg_replace('/\n\s*' . preg_quote($placeholder, '/') . '\s*\n/', "\n", $formattedContent); } } $formattedContent = preg_replace('/\n{3,}/', "\n\n", $formattedContent); return self::cleanContent($formattedContent); } }