| @@ -11,14 +11,12 @@ | ||
| 11 | 11 | |
| 12 | 12 | use Error; |
| 13 | 13 | use Exception; |
| 14 | 14 | use Templately\Utils\Helper; |
| 15 | -use Templately\Utils\Database; | |
| 16 | 15 | use WP_REST_Request; |
| 17 | 16 | use WP_Error; |
| 18 | 17 | use Templately\Core\Importer\Utils\Utils; |
| 19 | 18 | use Templately\Core\Importer\Utils\AIUtils; |
| 20 | -use Templately\Core\Importer\Utils\SignatureVerifier; | |
| 21 | 19 | use Templately\Core\Importer\Parsers\WXR_Parser; |
| 22 | 20 | |
| 23 | 21 | class AIContent extends API { |
| 24 | 22 | private $endpoint = 'ai-content'; |
| @@ -23,22 +21,9 @@ | ||
| 23 | 21 | class AIContent extends API { |
| 24 | 22 | private $endpoint = 'ai-content'; |
| 25 | 23 | private $dev_mode = false; |
| 26 | 24 | |
| 27 | - /** | |
| 28 | - * Short-lived cache of the `v2/chatbot/generated/{chat}` bundle. | |
| 29 | - * | |
| 30 | - * That payload is large (every generated page's block JSON, served off GCP) | |
| 31 | - * and the direct-import handoff pulls it twice within seconds — once to read | |
| 32 | - * the customization, once to write the pages. Only a COMPLETE bundle is ever | |
| 33 | - * reused (an incomplete one has to be re-pulled to pick up new pages), and | |
| 34 | - * the TTL is deliberately short so the `can_import` / already-imported gate | |
| 35 | - * cannot go meaningfully stale. | |
| 36 | - */ | |
| 37 | - const GENERATED_CACHE_KEY = 'chatbot_generated_'; | |
| 38 | - const GENERATED_CACHE_TTL = 60; | |
| 39 | 25 | |
| 40 | - | |
| 41 | 26 | /** |
| 42 | 27 | * AIContent constructor. |
| 43 | 28 | * |
| 44 | 29 | * @param string $file File path. |
| @@ -56,32 +41,12 @@ | ||
| 56 | 41 | $process_id = $this->get_param('process_id'); |
| 57 | 42 | |
| 58 | 43 | $_route = $request->get_route(); |
| 59 | 44 | if ('/templately/v1/ai-content/ai-update' === $_route || '/templately/v1/ai-content/ai-update-preview' === $_route) { |
| 60 | - Helper::log( [ | |
| 61 | - 'headers' => $request->get_headers(), | |
| 62 | - 'body' => $request->get_params(), | |
| 63 | - ], 'ai_update_request' ); | |
| 64 | - | |
| 65 | 45 | if (empty($process_id)) { |
| 66 | 46 | return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'calculate_credit', 400); |
| 67 | 47 | } |
| 68 | 48 | |
| 69 | - $header_api_key = sanitize_text_field($request->get_header('x_templately_apikey')); | |
| 70 | - if (empty($header_api_key)) { | |
| 71 | - $header_api_key = sanitize_text_field($request->get_header('X-Templately-Apikey')); | |
| 72 | - } | |
| 73 | - | |
| 74 | - // Validate API key from header against database | |
| 75 | - if (empty($header_api_key)) { | |
| 76 | - return $this->error('missing_api_key', __('Missing API key in header.', 'templately'), 'ai-content/permission', 403); | |
| 77 | - } | |
| 78 | - | |
| 79 | - $is_valid_key = $this->validate_api_key_in_db($header_api_key); | |
| 80 | - if (!$is_valid_key) { | |
| 81 | - return $this->error('invalid_api_key', __('Invalid API key provided in header.', 'templately'), 'ai-content/permission', 403); | |
| 82 | - } | |
| 83 | - | |
| 84 | 49 | // Check AI process data using API key-based storage |
| 85 | 50 | $ai_process_data = AIUtils::get_ai_process_data(); |
| 86 | 51 | if (is_array($ai_process_data) && !empty($ai_process_data[$process_id])) { |
| 87 | 52 | return true; |
| @@ -93,9 +58,10 @@ | ||
| 93 | 58 | // // Allow access to attachments endpoint |
| 94 | 59 | // if ('/templately/v1/ai-content/attachments' === $_route) { |
| 95 | 60 | // return true; |
| 96 | 61 | // } |
| 97 | - return parent::_permission_check($request); | |
| 62 | + | |
| 63 | + return parent::permission_check($request); | |
| 98 | 64 | } |
| 99 | 65 | |
| 100 | 66 | |
| 101 | 67 | public function register_routes() { |
| @@ -102,46 +68,8 @@ | ||
| 102 | 68 | // $this->get( $this->endpoint . '/calculate-credit', [ $this, 'calculate_credit' ] ); |
| 103 | 69 | $this->post($this->endpoint . '/modify-content', [$this, 'modify_content']); |
| 104 | 70 | $this->post($this->endpoint . '/ai-update', [$this, 'ai_update']); |
| 105 | 71 | $this->post($this->endpoint . '/ai-update-preview', [$this, 'ai_update_preview']); |
| 106 | - $this->post($this->endpoint . '/generate-tagline', [$this, 'generate_tagline']); | |
| 107 | - $this->get($this->endpoint . '/chatbot-conversation', [$this, 'get_chatbot_conversation'], [ | |
| 108 | - 'chat' => [ | |
| 109 | - 'required' => true, | |
| 110 | - 'sanitize_callback' => 'sanitize_text_field', | |
| 111 | - 'validate_callback' => function($param, $request, $key) { | |
| 112 | - return is_string($param) && strlen($param) > 0 && strlen($param) <= 128 && preg_match('/^[A-Za-z0-9\-_]+$/', $param); | |
| 113 | - }, | |
| 114 | - ], | |
| 115 | - ]); | |
| 116 | - $this->get($this->endpoint . '/chatbot-generated', [$this, 'get_chatbot_generated'], [ | |
| 117 | - 'chat' => [ | |
| 118 | - 'required' => true, | |
| 119 | - 'sanitize_callback' => 'sanitize_text_field', | |
| 120 | - 'validate_callback' => function($param, $request, $key) { | |
| 121 | - return is_string($param) && strlen($param) > 0 && strlen($param) <= 128 && preg_match('/^[A-Za-z0-9\-_]+$/', $param); | |
| 122 | - }, | |
| 123 | - ], | |
| 124 | - ]); | |
| 125 | - $this->post($this->endpoint . '/chatbot-detected-info', [$this, 'update_chatbot_detected_info'], [ | |
| 126 | - 'chat' => [ | |
| 127 | - 'required' => true, | |
| 128 | - 'sanitize_callback' => 'sanitize_text_field', | |
| 129 | - 'validate_callback' => function($param, $request, $key) { | |
| 130 | - return is_string($param) && strlen($param) > 0 && strlen($param) <= 128 && preg_match('/^[A-Za-z0-9\-_]+$/', $param); | |
| 131 | - }, | |
| 132 | - ], | |
| 133 | - ]); | |
| 134 | - $this->post($this->endpoint . '/chatbot-import-prepare', [$this, 'chatbot_import_prepare']); | |
| 135 | - $this->post($this->endpoint . '/chatbot-mark-imported', [$this, 'mark_chatbot_imported'], [ | |
| 136 | - 'chat' => [ | |
| 137 | - 'required' => true, | |
| 138 | - 'sanitize_callback' => 'sanitize_text_field', | |
| 139 | - 'validate_callback' => function($param, $request, $key) { | |
| 140 | - return is_string($param) && strlen($param) > 0 && strlen($param) <= 128 && preg_match('/^[A-Za-z0-9\-_]+$/', $param); | |
| 141 | - }, | |
| 142 | - ], | |
| 143 | - ]); | |
| 144 | 72 | $this->get($this->endpoint . '/attachments', [$this, 'get_attachments'], [ |
| 145 | 73 | 'type' => [ |
| 146 | 74 | 'default' => 'pack', |
| 147 | 75 | 'required' => false, |
| @@ -230,9 +158,9 @@ | ||
| 230 | 158 | |
| 231 | 159 | |
| 232 | 160 | // return $response; |
| 233 | 161 | if (is_wp_error($response)) { |
| 234 | - return $this->error('request_failed', __('Request failed.', 'templately'), 'calculate_credit', 500, ['error_detail' => $response->get_error_message()]); | |
| 162 | + return $this->error('request_failed', __('Request failed.', 'templately'), 'calculate_credit', 500, $response); | |
| 235 | 163 | } |
| 236 | 164 | |
| 237 | 165 | $body = wp_remote_retrieve_body($response); |
| 238 | 166 | $data = json_decode($body, true); |
| @@ -254,31 +182,20 @@ | ||
| 254 | 182 | $isBusinessNichesNew = $this->get_param('isBusinessNichesNew', false); |
| 255 | 183 | $ai_page_ids = $this->get_param('ai_page_ids', [], null); |
| 256 | 184 | $content_ids = $this->get_param('content_ids', [], null); |
| 257 | 185 | $session_id = $this->get_param('session_id'); // Add session_id parameter |
| 258 | - | |
| 259 | - // Security: Sanitize session_id if provided | |
| 260 | - if (!empty($session_id)) { | |
| 261 | - $session_id = AIUtils::sanitize_path_component($session_id, 'session_id'); | |
| 262 | - if (is_wp_error($session_id)) { | |
| 263 | - return $session_id; | |
| 264 | - } | |
| 265 | - } | |
| 266 | - | |
| 267 | 186 | $preview_pages = $this->get_param('preview_pages', [], null); |
| 268 | 187 | $image_replace = $this->get_param('imageReplace', [], null); |
| 269 | 188 | $platform = $this->get_param('platform'); |
| 270 | - $language = $this->get_param('language', null); | |
| 271 | 189 | |
| 272 | 190 | // ai content fields |
| 273 | - $name = $this->get_param('name'); | |
| 274 | - $category = $this->get_param('category'); | |
| 275 | - $description = $this->get_param('description'); | |
| 276 | - $email = $this->get_param('email'); | |
| 277 | - $contactNumber = $this->get_param('contactNumber'); | |
| 278 | - $businessAddress = $this->get_param('businessAddress'); | |
| 279 | - $openingHour = $this->get_param('openingHour'); | |
| 280 | - $requested_platform = $this->get_param('requested_platform', 'templately'); | |
| 191 | + $name = $this->get_param('name'); | |
| 192 | + $category = $this->get_param('category'); | |
| 193 | + $description = $this->get_param('description'); | |
| 194 | + $email = $this->get_param('email'); | |
| 195 | + $contactNumber = $this->get_param('contactNumber'); | |
| 196 | + $businessAddress = $this->get_param('businessAddress'); | |
| 197 | + $openingHour = $this->get_param('openingHour'); | |
| 281 | 198 | |
| 282 | 199 | if (empty($pack_id)) { |
| 283 | 200 | return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'modify_content', 400); |
| 284 | 201 | } |
| @@ -296,11 +213,10 @@ | ||
| 296 | 213 | // $response = get_transient( '__templately_ai_process_id' ); |
| 297 | 214 | |
| 298 | 215 | // if(empty($response)) { |
| 299 | 216 | $extra_headers = [ |
| 300 | - 'Accept' => 'application/json', | |
| 301 | - 'x-templately-session-id' => $session_id, | |
| 302 | - 'x-templately-requested-platform' => $requested_platform, | |
| 217 | + 'Accept' => 'application/json', | |
| 218 | + 'x-templately-session-id' => $session_id, | |
| 303 | 219 | ]; |
| 304 | 220 | $body_data = [ |
| 305 | 221 | 'business_name' => $name, |
| 306 | 222 | 'business_niches' => $category, |
| @@ -312,20 +228,10 @@ | ||
| 312 | 228 | 'pack_id' => $pack_id, |
| 313 | 229 | 'content_ids' => $content_ids, |
| 314 | 230 | 'platform' => $platform, |
| 315 | 231 | 'preview_pages' => $preview_pages, |
| 316 | - 'language' => $language, | |
| 317 | 232 | 'callback' => defined('TEMPLATELY_CALLBACK') ? TEMPLATELY_CALLBACK . '/wp-json/templately/v1/ai-content/ai-update' : rest_url('templately/v1/ai-content/ai-update'), |
| 318 | 233 | ]; |
| 319 | - /** | |
| 320 | - * Filter body data before making API request to modify-content endpoint | |
| 321 | - * | |
| 322 | - * @since 3.5.0 | |
| 323 | - * @param array $body_data The request body data | |
| 324 | - * @param WP_REST_Request $request The REST request object | |
| 325 | - */ | |
| 326 | - $body_data = apply_filters( 'templately_ai_modify_content_body_data', $body_data, $this->request ); | |
| 327 | - | |
| 328 | 234 | $response = Helper::make_api_post_request('v2/ai/modify-content/pack', $body_data, $extra_headers, 15 * MINUTE_IN_SECONDS); |
| 329 | 235 | |
| 330 | 236 | // set_transient( '__templately_ai_process_id', $response, 60 * 60 * 24 * 30 ); |
| 331 | 237 | // } |
| @@ -338,9 +244,9 @@ | ||
| 338 | 244 | |
| 339 | 245 | // return $response; |
| 340 | 246 | if (is_wp_error($response)) { |
| 341 | 247 | error_log(print_r($response, true)); |
| 342 | - return $this->error('request_failed', __('Request failed.', 'templately'), 'modify_content', 500, ['error_data' => $response->get_error_data()]); | |
| 248 | + return $this->error('request_failed', __('Request failed.', 'templately'), 'modify_content', 500, $response->additional_data); | |
| 343 | 249 | } |
| 344 | 250 | |
| 345 | 251 | $body = wp_remote_retrieve_body($response); |
| 346 | 252 | $data = json_decode($body, true); |
| @@ -345,9 +251,9 @@ | ||
| 345 | 251 | $body = wp_remote_retrieve_body($response); |
| 346 | 252 | $data = json_decode($body, true); |
| 347 | 253 | // error status is ok, if status is error then return as is |
| 348 | 254 | if (! is_array($data) || ! isset($data['status'])) { |
| 349 | - return $this->error('invalid_response', __('Invalid response.', 'templately'), 'modify_content', 500, ['data' => $data]); | |
| 255 | + return $this->error('invalid_response', __('Invalid response.', 'templately'), 'modify_content', 500, $data); | |
| 350 | 256 | } |
| 351 | 257 | |
| 352 | 258 | // "{"status":"success","message":"The content is being generated in the queue","process_id":"01JRQQD39GNWTNF18EWF8YH0BG-271838-pack-408"}" |
| 353 | 259 | if (isset($data['status']) && $data['status'] === 'success' && isset($data['process_id'])) { |
| @@ -376,27 +282,25 @@ | ||
| 376 | 282 | |
| 377 | 283 | $user = $this->utils('options')->get('user'); |
| 378 | 284 | |
| 379 | 285 | $ai_process_data[$process_id] = [ |
| 380 | - 'name' => $name, | |
| 381 | - 'category' => $category, | |
| 382 | - 'description' => $description, | |
| 383 | - 'email' => $email, | |
| 384 | - 'contactNumber' => $contactNumber, | |
| 385 | - 'businessAddress' => $businessAddress, | |
| 386 | - 'openingHour' => $openingHour, | |
| 387 | - 'process_id' => $process_id, | |
| 388 | - 'pack_id' => $pack_id, | |
| 389 | - 'ai_page_ids' => $ai_page_ids, | |
| 390 | - 'ai_preview_ids' => $preview_pages, | |
| 391 | - 'content_ids' => $content_ids, | |
| 392 | - 'platform' => $platform, | |
| 393 | - 'api_key' => $this->api_key, | |
| 394 | - 'user_id' => isset($user['id']) ? $user['id'] : null, | |
| 395 | - 'session_id' => $session_id, | |
| 396 | - 'imageReplace' => $image_replace, | |
| 397 | - 'language' => $language, | |
| 398 | - 'requested_platform' => $requested_platform, | |
| 286 | + 'name' => $name, | |
| 287 | + 'category' => $category, | |
| 288 | + 'description' => $description, | |
| 289 | + 'email' => $email, | |
| 290 | + 'contactNumber' => $contactNumber, | |
| 291 | + 'businessAddress' => $businessAddress, | |
| 292 | + 'openingHour' => $openingHour, | |
| 293 | + 'process_id' => $process_id, | |
| 294 | + 'pack_id' => $pack_id, | |
| 295 | + 'ai_page_ids' => $ai_page_ids, | |
| 296 | + 'ai_preview_ids' => $preview_pages, | |
| 297 | + 'content_ids' => $content_ids, | |
| 298 | + 'platform' => $platform, | |
| 299 | + 'api_key' => $this->api_key, | |
| 300 | + 'user_id' => isset($user['id']) ? $user['id'] : null, | |
| 301 | + 'session_id' => $session_id, // Store session_id for coordination | |
| 302 | + 'imageReplace' => $image_replace, // Store session_id for coordination | |
| 399 | 303 | ]; |
| 400 | 304 | |
| 401 | 305 | // Update using API key-based storage with automatic count-based cleanup |
| 402 | 306 | AIUtils::update_ai_process_data($ai_process_data); |
| @@ -553,20 +457,17 @@ | ||
| 553 | 457 | ), |
| 554 | 458 | ]; |
| 555 | 459 | } |
| 556 | 460 | |
| 557 | - | |
| 558 | - | |
| 559 | 461 | /** |
| 560 | 462 | * Get attachments from API endpoint |
| 561 | 463 | * |
| 562 | - * @return array|\WP_Error | |
| 464 | + * @return array | |
| 563 | 465 | */ |
| 564 | 466 | public function get_attachments() { |
| 565 | 467 | // Get parameters from request |
| 566 | - $type = $this->get_param('type', 'pack'); | |
| 567 | - $id = $this->get_param('pack_id'); | |
| 568 | - $requested_platform = $this->get_param('requested_platform', 'templately'); | |
| 468 | + $type = $this->get_param('type', 'pack'); | |
| 469 | + $id = $this->get_param('pack_id'); | |
| 569 | 470 | |
| 570 | 471 | // Require ID parameter - return error if not provided |
| 571 | 472 | if (empty($id)) { |
| 572 | 473 | return $this->error('missing_id', __('Pack ID or ID parameter is required.', 'templately'), 'get_attachments', 400); |
| @@ -577,16 +478,15 @@ | ||
| 577 | 478 | $api_endpoint = "get-xml-attachment/{$type}/{$id}"; |
| 578 | 479 | |
| 579 | 480 | // Make API call |
| 580 | 481 | $extra_headers = [ |
| 581 | - 'Accept' => 'application/xml, text/xml', | |
| 582 | - 'x-templately-requested-platform' => $requested_platform, | |
| 482 | + 'Accept' => 'application/xml, text/xml', | |
| 583 | 483 | ]; |
| 584 | 484 | $response = Helper::make_api_get_request("v2/$api_endpoint", [], $extra_headers, 30); |
| 585 | 485 | |
| 586 | 486 | // Check for HTTP errors |
| 587 | 487 | if (is_wp_error($response)) { |
| 588 | - return $this->error('api_request_failed', __('Failed to fetch attachments from API.', 'templately'), 'get_attachments', 500, ['error_detail' => $response->get_error_message()]); | |
| 488 | + return $this->error('api_request_failed', __('Failed to fetch attachments from API.', 'templately'), 'get_attachments', 500, $response->get_error_message()); | |
| 589 | 489 | } |
| 590 | 490 | |
| 591 | 491 | $response_code = wp_remote_retrieve_response_code($response); |
| 592 | 492 | $xml_content = wp_remote_retrieve_body($response); |
| @@ -609,9 +509,9 @@ | ||
| 609 | 509 | // Parse the XML content from API response |
| 610 | 510 | $parsed_data = $this->parse_xml_content($xml_content); |
| 611 | 511 | |
| 612 | 512 | if (is_wp_error($parsed_data)) { |
| 613 | - return $this->error('xml_parse_error', __('Failed to parse XML content.', 'templately'), 'get_attachments', 500, ['error_detail' => $parsed_data->get_error_message()]); | |
| 513 | + return $this->error('xml_parse_error', __('Failed to parse XML content.', 'templately'), 'get_attachments', 500, $parsed_data->get_error_message()); | |
| 614 | 514 | } |
| 615 | 515 | |
| 616 | 516 | // Extract attachments from parsed data |
| 617 | 517 | $attachments = $this->extract_attachments_from_parsed_data($parsed_data); |
| @@ -622,9 +522,9 @@ | ||
| 622 | 522 | 'message' => sprintf(__('Found %d attachments.', 'templately'), count($attachments)), |
| 623 | 523 | ]; |
| 624 | 524 | |
| 625 | 525 | } catch (Exception $e) { |
| 626 | - return $this->error('exception', __('An unexpected error occurred while fetching attachments.', 'templately'), 'get_attachments', 500, ['error_detail' => $e->getMessage()]); | |
| 526 | + return $this->error('exception', __('An unexpected error occurred while fetching attachments.', 'templately'), 'get_attachments', 500, $e->getMessage()); | |
| 627 | 527 | } |
| 628 | 528 | } |
| 629 | 529 | |
| 630 | 530 | |
| @@ -632,9 +532,9 @@ | ||
| 632 | 532 | /** |
| 633 | 533 | * Parse XML content string using WXR Parser |
| 634 | 534 | * |
| 635 | 535 | * @param string $xml_content XML content string |
| 636 | - * @return array|\WP_Error Parsed data or error | |
| 536 | + * @return array|WP_Error Parsed data or error | |
| 637 | 537 | */ |
| 638 | 538 | private function parse_xml_content($xml_content) { |
| 639 | 539 | // Ensure WordPress filesystem functions are available |
| 640 | 540 | if (!function_exists('wp_tempnam')) { |
| @@ -886,747 +786,6 @@ | ||
| 886 | 786 | 'page' => $current_page, |
| 887 | 787 | 'per_page' => $per_page_count, |
| 888 | 788 | 'total_pages' => $total_results > 0 ? ceil($total_results / $per_page_count) : 0, |
| 889 | 789 | ]); |
| 890 | - } | |
| 891 | - | |
| 892 | - | |
| 893 | - | |
| 894 | - /** | |
| 895 | - * Generate tagline using AI | |
| 896 | - * | |
| 897 | - * @return array|WP_Error | |
| 898 | - */ | |
| 899 | - public function generate_tagline() { | |
| 900 | - // Get parameters | |
| 901 | - $prompt = $this->get_param('prompt'); | |
| 902 | - $requested_platform = $this->get_param('requested_platform', 'templately'); | |
| 903 | - | |
| 904 | - // Validate required parameters | |
| 905 | - if (empty($prompt)) { | |
| 906 | - return $this->error( | |
| 907 | - 'missing_prompt', | |
| 908 | - __('Prompt is required for tagline generation.', 'templately'), | |
| 909 | - 'generate_tagline', | |
| 910 | - 400 | |
| 911 | - ); | |
| 912 | - } | |
| 913 | - | |
| 914 | - // Prepare request body | |
| 915 | - $body_data = [ | |
| 916 | - 'prompt' => $prompt, | |
| 917 | - ]; | |
| 918 | - | |
| 919 | - // Make API request | |
| 920 | - $extra_headers = [ | |
| 921 | - 'Content-Type' => 'application/json', | |
| 922 | - 'x-templately-requested-platform' => $requested_platform, | |
| 923 | - ]; | |
| 924 | - | |
| 925 | - $response = Helper::make_api_post_request('v2/generate-tagline', $body_data, $extra_headers, 30); | |
| 926 | - | |
| 927 | - // Handle API response errors | |
| 928 | - if (is_wp_error($response)) { | |
| 929 | - return $this->error( | |
| 930 | - 'api_request_failed', | |
| 931 | - __('Failed to generate tagline.', 'templately'), | |
| 932 | - 'generate_tagline', | |
| 933 | - 500, | |
| 934 | - ['error_detail' => $response->get_error_message()] | |
| 935 | - ); | |
| 936 | - } | |
| 937 | - | |
| 938 | - $response_code = wp_remote_retrieve_response_code($response); | |
| 939 | - $response_body = wp_remote_retrieve_body($response); | |
| 940 | - | |
| 941 | - if ($response_code !== 200) { | |
| 942 | - // Try to parse the response body as JSON to get specific error details | |
| 943 | - $data = json_decode($response_body, true); | |
| 944 | - | |
| 945 | - // If valid JSON, extract error message and return with proper status code | |
| 946 | - if (json_last_error() === JSON_ERROR_NONE && is_array($data)) { | |
| 947 | - $error_message = isset($data['message']) ? $data['message'] : __('Something went wrong. Please try again or contact support.', 'templately'); | |
| 948 | - return $this->error( | |
| 949 | - 'api_response_error', | |
| 950 | - $error_message, | |
| 951 | - 'generate_tagline', | |
| 952 | - $response_code | |
| 953 | - ); | |
| 954 | - } | |
| 955 | - | |
| 956 | - // Otherwise, return generic error | |
| 957 | - return $this->error( | |
| 958 | - 'api_response_error', | |
| 959 | - __('Something went wrong. Please try again or contact support.', 'templately'), | |
| 960 | - 'generate_tagline', | |
| 961 | - $response_code | |
| 962 | - ); | |
| 963 | - } | |
| 964 | - | |
| 965 | - // Parse and validate response | |
| 966 | - $data = json_decode($response_body, true); | |
| 967 | - if (json_last_error() !== JSON_ERROR_NONE) { | |
| 968 | - return $this->error( | |
| 969 | - 'invalid_response', | |
| 970 | - __('Invalid response from API.', 'templately'), | |
| 971 | - 'generate_tagline', | |
| 972 | - 500 | |
| 973 | - ); | |
| 974 | - } | |
| 975 | - | |
| 976 | - // Check if the response has the expected structure | |
| 977 | - if (!isset($data['status'])) { | |
| 978 | - return $this->error( | |
| 979 | - 'api_response_error', | |
| 980 | - __('API returned an unexpected response.', 'templately'), | |
| 981 | - 'generate_tagline', | |
| 982 | - 500 | |
| 983 | - ); | |
| 984 | - } | |
| 985 | - | |
| 986 | - // Return the response as-is | |
| 987 | - return $data; | |
| 988 | - } | |
| 989 | - | |
| 990 | - /** | |
| 991 | - * Fetch a chatbot conversation by ID from the external Templately chatbot API. | |
| 992 | - * | |
| 993 | - * Used to resume a conversation that began on templately.dev when the user | |
| 994 | - * is redirected into the plugin with ?process=ai&chat={uuid}. | |
| 995 | - * | |
| 996 | - * @return array|\WP_Error Pass-through of the external response { status, data } or WP_Error. | |
| 997 | - */ | |
| 998 | - public function get_chatbot_conversation() { | |
| 999 | - $chat = $this->get_param('chat'); | |
| 1000 | - | |
| 1001 | - if (empty($chat)) { | |
| 1002 | - return $this->error('invalid_chat_id', __('Invalid conversation ID.', 'templately'), 'ai-content/chatbot-conversation', 400); | |
| 1003 | - } | |
| 1004 | - | |
| 1005 | - $extra_headers = [ | |
| 1006 | - 'Accept' => 'application/json', | |
| 1007 | - ]; | |
| 1008 | - $response = Helper::make_api_get_request("v2/chatbot/conversation/{$chat}", [], $extra_headers, 30); | |
| 1009 | - | |
| 1010 | - if (is_wp_error($response)) { | |
| 1011 | - return $this->error('request_failed', __('Failed to fetch conversation.', 'templately'), 'ai-content/chatbot-conversation', 500, ['error_detail' => $response->get_error_message()]); | |
| 1012 | - } | |
| 1013 | - | |
| 1014 | - $response_code = wp_remote_retrieve_response_code($response); | |
| 1015 | - $body = wp_remote_retrieve_body($response); | |
| 1016 | - $data = json_decode($body, true); | |
| 1017 | - | |
| 1018 | - if ($response_code !== 200) { | |
| 1019 | - $message = (is_array($data) && !empty($data['message'])) ? $data['message'] : sprintf(__('API returned HTTP %d error.', 'templately'), $response_code); | |
| 1020 | - return $this->error('api_http_error', $message, 'ai-content/chatbot-conversation', $response_code); | |
| 1021 | - } | |
| 1022 | - | |
| 1023 | - if (!is_array($data) || !isset($data['status'])) { | |
| 1024 | - return $this->error('invalid_response', __('Invalid response.', 'templately'), 'ai-content/chatbot-conversation', 500); | |
| 1025 | - } | |
| 1026 | - | |
| 1027 | - return $data; | |
| 1028 | - } | |
| 1029 | - | |
| 1030 | - /** | |
| 1031 | - * Fetch the server-side generated content for a chatbot conversation (Phase 2). | |
| 1032 | - * | |
| 1033 | - * In Phase 2 the AI content is generated on the backend. This proxy mirrors | |
| 1034 | - * {@see get_chatbot_conversation()} and returns the already-generated page | |
| 1035 | - * content, customization data and signed logo URL so the plugin can run a | |
| 1036 | - * thin import without triggering generation or the customizer locally. | |
| 1037 | - * | |
| 1038 | - * @return array|\WP_Error Pass-through of the external response { status, data } or WP_Error. | |
| 1039 | - */ | |
| 1040 | - public function get_chatbot_generated() { | |
| 1041 | - $chat = $this->get_param('chat'); | |
| 1042 | - | |
| 1043 | - if (empty($chat)) { | |
| 1044 | - return $this->error('invalid_chat_id', __('Invalid conversation ID.', 'templately'), 'ai-content/chatbot-generated', 400); | |
| 1045 | - } | |
| 1046 | - | |
| 1047 | - $extra_headers = [ | |
| 1048 | - 'Accept' => 'application/json', | |
| 1049 | - ]; | |
| 1050 | - $response = Helper::make_api_get_request("v2/chatbot/generated/{$chat}", [], $extra_headers, 30); | |
| 1051 | - | |
| 1052 | - if (is_wp_error($response)) { | |
| 1053 | - return $this->error('request_failed', __('Failed to fetch generated content.', 'templately'), 'ai-content/chatbot-generated', 500, ['error_detail' => $response->get_error_message()]); | |
| 1054 | - } | |
| 1055 | - | |
| 1056 | - $response_code = wp_remote_retrieve_response_code($response); | |
| 1057 | - $body = wp_remote_retrieve_body($response); | |
| 1058 | - $data = json_decode($body, true); | |
| 1059 | - | |
| 1060 | - if ($response_code !== 200) { | |
| 1061 | - $message = (is_array($data) && !empty($data['message'])) ? $data['message'] : sprintf(__('API returned HTTP %d error.', 'templately'), $response_code); | |
| 1062 | - return $this->error('api_http_error', $message, 'ai-content/chatbot-generated', $response_code); | |
| 1063 | - } | |
| 1064 | - | |
| 1065 | - if (!is_array($data) || !isset($data['status'])) { | |
| 1066 | - return $this->error('invalid_response', __('Invalid response.', 'templately'), 'ai-content/chatbot-generated', 500); | |
| 1067 | - } | |
| 1068 | - | |
| 1069 | - // The direct-import handoff reads this endpoint and then immediately calls | |
| 1070 | - // chatbot-import-prepare, which pulls the very same (large) bundle off GCP | |
| 1071 | - // seconds later. Park it so prepare can reuse it instead of paying for a | |
| 1072 | - // second identical transfer. | |
| 1073 | - Database::set_transient(self::GENERATED_CACHE_KEY . $chat, $data, self::GENERATED_CACHE_TTL); | |
| 1074 | - | |
| 1075 | - return $data; | |
| 1076 | - } | |
| 1077 | - | |
| 1078 | - /** | |
| 1079 | - * Persist edited detected-info back to the chatbot conversation (Phase 2). | |
| 1080 | - * | |
| 1081 | - * Mirrors {@see get_chatbot_conversation()} / {@see get_chatbot_generated()} | |
| 1082 | - * but forwards a POST. When the user edits the detected-info card in the | |
| 1083 | - * sidebar, the plugin proxies the corrected values to the backend so a later | |
| 1084 | - * replay reflects them. The backend route is gated by the X-Templately-Apikey | |
| 1085 | - * header, so it is supplied explicitly here. | |
| 1086 | - * | |
| 1087 | - * Expected JSON body: { chat, detected_info: { ...fields } } | |
| 1088 | - * | |
| 1089 | - * @return array|\WP_Error Pass-through of the external response { status, data } or WP_Error. | |
| 1090 | - */ | |
| 1091 | - public function update_chatbot_detected_info() { | |
| 1092 | - $chat = $this->get_param('chat'); | |
| 1093 | - $detected_info = $this->get_param('detected_info', [], null); | |
| 1094 | - | |
| 1095 | - if (empty($chat)) { | |
| 1096 | - return $this->error('invalid_chat_id', __('Invalid conversation ID.', 'templately'), 'ai-content/chatbot-detected-info', 400); | |
| 1097 | - } | |
| 1098 | - | |
| 1099 | - // detected_info may arrive as a JSON string when sent via FormData. | |
| 1100 | - if (is_string($detected_info)) { | |
| 1101 | - $decoded = json_decode($detected_info, true); | |
| 1102 | - $detected_info = is_array($decoded) ? $decoded : []; | |
| 1103 | - } | |
| 1104 | - if (!is_array($detected_info)) { | |
| 1105 | - $detected_info = []; | |
| 1106 | - } | |
| 1107 | - | |
| 1108 | - $extra_headers = [ | |
| 1109 | - 'Accept' => 'application/json', | |
| 1110 | - 'X-Templately-Apikey' => $this->api_key, | |
| 1111 | - ]; | |
| 1112 | - $response = Helper::make_api_post_request("v2/chatbot/conversation/{$chat}/detected-info", ['detected_info' => $detected_info], $extra_headers, 30); | |
| 1113 | - | |
| 1114 | - if (is_wp_error($response)) { | |
| 1115 | - return $this->error('request_failed', __('Failed to update detected info.', 'templately'), 'ai-content/chatbot-detected-info', 500, ['error_detail' => $response->get_error_message()]); | |
| 1116 | - } | |
| 1117 | - | |
| 1118 | - $response_code = wp_remote_retrieve_response_code($response); | |
| 1119 | - $body = wp_remote_retrieve_body($response); | |
| 1120 | - $data = json_decode($body, true); | |
| 1121 | - | |
| 1122 | - if ($response_code !== 200) { | |
| 1123 | - $message = (is_array($data) && !empty($data['message'])) ? $data['message'] : sprintf(__('API returned HTTP %d error.', 'templately'), $response_code); | |
| 1124 | - return $this->error('api_http_error', $message, 'ai-content/chatbot-detected-info', $response_code); | |
| 1125 | - } | |
| 1126 | - | |
| 1127 | - if (!is_array($data) || !isset($data['status'])) { | |
| 1128 | - return $this->error('invalid_response', __('Invalid response.', 'templately'), 'ai-content/chatbot-detected-info', 500); | |
| 1129 | - } | |
| 1130 | - | |
| 1131 | - return $data; | |
| 1132 | - } | |
| 1133 | - | |
| 1134 | - /** | |
| 1135 | - * Report a completed import back to templately.dev (Phase 2 import-once gate). | |
| 1136 | - * | |
| 1137 | - * Once the plugin finishes importing the generated content for a conversation, | |
| 1138 | - * it calls this so the backend flips the conversation status to `imported`. | |
| 1139 | - * Subsequent pulls then return `already_imported = true`, and the web/plugin | |
| 1140 | - * UIs refuse a second import. | |
| 1141 | - * | |
| 1142 | - * @return array|\WP_Error | |
| 1143 | - */ | |
| 1144 | - public function mark_chatbot_imported() { | |
| 1145 | - $chat = $this->get_param('chat'); | |
| 1146 | - | |
| 1147 | - if (empty($chat)) { | |
| 1148 | - return $this->error('invalid_chat_id', __('Invalid conversation ID.', 'templately'), 'ai-content/chatbot-mark-imported', 400); | |
| 1149 | - } | |
| 1150 | - | |
| 1151 | - $extra_headers = [ | |
| 1152 | - 'Accept' => 'application/json', | |
| 1153 | - 'X-Templately-Apikey' => $this->api_key, | |
| 1154 | - ]; | |
| 1155 | - $response = Helper::make_api_post_request("v2/chatbot/conversation/{$chat}/imported", [], $extra_headers, 30); | |
| 1156 | - | |
| 1157 | - if (is_wp_error($response)) { | |
| 1158 | - return $this->error('request_failed', __('Failed to record import.', 'templately'), 'ai-content/chatbot-mark-imported', 500, ['error_detail' => $response->get_error_message()]); | |
| 1159 | - } | |
| 1160 | - | |
| 1161 | - $response_code = wp_remote_retrieve_response_code($response); | |
| 1162 | - $body = wp_remote_retrieve_body($response); | |
| 1163 | - $data = json_decode($body, true); | |
| 1164 | - | |
| 1165 | - if ($response_code !== 200) { | |
| 1166 | - $message = (is_array($data) && !empty($data['message'])) ? $data['message'] : sprintf(__('API returned HTTP %d error.', 'templately'), $response_code); | |
| 1167 | - return $this->error('api_http_error', $message, 'ai-content/chatbot-mark-imported', $response_code); | |
| 1168 | - } | |
| 1169 | - | |
| 1170 | - if (!is_array($data) || !isset($data['status'])) { | |
| 1171 | - return $this->error('invalid_response', __('Invalid response.', 'templately'), 'ai-content/chatbot-mark-imported', 500); | |
| 1172 | - } | |
| 1173 | - | |
| 1174 | - return $data; | |
| 1175 | - } | |
| 1176 | - | |
| 1177 | - /** | |
| 1178 | - * Thin importer prepare step (Phase 2). | |
| 1179 | - * | |
| 1180 | - * Given a chat uuid and a session that has already been created and had its | |
| 1181 | - * pack downloaded (via the existing templately_pack_create_session_and_download | |
| 1182 | - * AJAX flow), this: | |
| 1183 | - * 1. Registers AI process data (including `chat_id`) so ai_get_json()/ | |
| 1184 | - * validation keep working AND so the Finalizer's ChatAIContentProvider | |
| 1185 | - * can claim this process. | |
| 1186 | - * 2. Fetches the backend-generated page content for the conversation. | |
| 1187 | - * 3. Writes whatever pages are ALREADY generated to the same .ai.json | |
| 1188 | - * location the legacy flow uses (via AIUtils::save_template_to_file). | |
| 1189 | - * 4. Downloads the signed logo URL into the WP media library (Utils::upload_logo). | |
| 1190 | - * | |
| 1191 | - * This endpoint NEVER waits for generation to complete. Pages still being | |
| 1192 | - * generated are reported in `missing` and are pulled on demand — and waited | |
| 1193 | - * for — by the Finalizer via AIContentResolver. Previously this held the | |
| 1194 | - * client in a 3s poll loop until every page was ready, which delayed the | |
| 1195 | - * start of the import by minutes for no benefit. | |
| 1196 | - * | |
| 1197 | - * It returns the resolved customization data, logo attachment and the | |
| 1198 | - * process_id so the React app can build the settings FormData and run the | |
| 1199 | - * existing import. No generation or local customizer is involved. | |
| 1200 | - * | |
| 1201 | - * Expected JSON body: { chat, session_id, ai_page_ids: { 'content/page': [...], templates: [...] } } | |
| 1202 | - * | |
| 1203 | - * @return array|\WP_Error | |
| 1204 | - */ | |
| 1205 | - /** | |
| 1206 | - * Does a `v2/chatbot/generated` bundle already carry every expected page? | |
| 1207 | - * | |
| 1208 | - * A page counts as present when it is in `templates` (string or int key, the | |
| 1209 | - * upstream is inconsistent) or listed in `skipped_pages` — a skipped page is | |
| 1210 | - * never coming, so waiting on it would hang the poll until it timed out. | |
| 1211 | - * | |
| 1212 | - * @param array $data Decoded `{ status, data }` bundle. | |
| 1213 | - * @param array $expected_ids Flattened page ids, as strings. | |
| 1214 | - * @return bool | |
| 1215 | - */ | |
| 1216 | - private function is_generated_bundle_complete($data, $expected_ids) { | |
| 1217 | - $generated = isset($data['data']) && is_array($data['data']) ? $data['data'] : []; | |
| 1218 | - | |
| 1219 | - // Never reuse a bundle the user is no longer allowed to import. | |
| 1220 | - if (isset($generated['can_import']) && ! $generated['can_import']) { | |
| 1221 | - return false; | |
| 1222 | - } | |
| 1223 | - | |
| 1224 | - $templates = isset($generated['templates']) && is_array($generated['templates']) ? $generated['templates'] : []; | |
| 1225 | - $skipped = isset($generated['skipped_pages']) && is_array($generated['skipped_pages']) ? array_map('strval', $generated['skipped_pages']) : []; | |
| 1226 | - | |
| 1227 | - if (empty($templates) && empty($skipped)) { | |
| 1228 | - return false; | |
| 1229 | - } | |
| 1230 | - | |
| 1231 | - foreach ($expected_ids as $id) { | |
| 1232 | - if (array_key_exists($id, $templates) || array_key_exists((int) $id, $templates) || in_array($id, $skipped, true)) { | |
| 1233 | - continue; | |
| 1234 | - } | |
| 1235 | - return false; | |
| 1236 | - } | |
| 1237 | - | |
| 1238 | - return true; | |
| 1239 | - } | |
| 1240 | - | |
| 1241 | - /** | |
| 1242 | - * Resolve the conversation answers to store on a chat-driven process. | |
| 1243 | - * | |
| 1244 | - * Prefers what the client sent (the sidebar holds the detected info the user | |
| 1245 | - * may have just edited), then what was already stored for this process (so a | |
| 1246 | - * repeat call costs nothing), and only then pulls the conversation from the | |
| 1247 | - * cloud — which is the path the `?process=import` landing takes, since it | |
| 1248 | - * never opens the sidebar and so has no answers to send. | |
| 1249 | - * | |
| 1250 | - * A failure here must never break the import: it returns an empty array and | |
| 1251 | - * the process is stored exactly as before. | |
| 1252 | - * | |
| 1253 | - * @param string $chat Conversation uuid. | |
| 1254 | - * @param mixed $detected_info Raw `detected_info` sent by the client. | |
| 1255 | - * @param array $ai_process_data All stored process data. | |
| 1256 | - * @param string $process_id This process id. | |
| 1257 | - * @return array<string,string> Map of conversation step key => value. | |
| 1258 | - */ | |
| 1259 | - private function resolve_chat_conversation_fields($chat, $detected_info, $ai_process_data, $process_id) { | |
| 1260 | - $mapped = AIUtils::map_chat_detected_info($detected_info); | |
| 1261 | - if (!empty($mapped)) { | |
| 1262 | - return $mapped; | |
| 1263 | - } | |
| 1264 | - | |
| 1265 | - // Already resolved on an earlier call for this process — reuse it. | |
| 1266 | - if (isset($ai_process_data[$process_id]) && AIUtils::has_conversation_data($ai_process_data[$process_id])) { | |
| 1267 | - return AIUtils::map_chat_detected_info( | |
| 1268 | - array_intersect_key($ai_process_data[$process_id], array_flip(AIUtils::CONVERSATION_FIELDS)) | |
| 1269 | - ); | |
| 1270 | - } | |
| 1271 | - | |
| 1272 | - $response = Helper::make_api_get_request("v2/chatbot/conversation/{$chat}", [], ['Accept' => 'application/json'], 30); | |
| 1273 | - if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) { | |
| 1274 | - Helper::log(sprintf('chatbot_import_prepare[%s] conversation fetch failed — process stored without answers', $chat), 'ai-import', 'warning'); | |
| 1275 | - return []; | |
| 1276 | - } | |
| 1277 | - | |
| 1278 | - $data = json_decode(wp_remote_retrieve_body($response), true); | |
| 1279 | - if (!is_array($data) || empty($data['data']['detected_info'])) { | |
| 1280 | - return []; | |
| 1281 | - } | |
| 1282 | - | |
| 1283 | - return AIUtils::map_chat_detected_info($data['data']['detected_info']); | |
| 1284 | - } | |
| 1285 | - | |
| 1286 | - public function chatbot_import_prepare() { | |
| 1287 | - add_filter('wp_redirect', '__return_false', 999); | |
| 1288 | - set_time_limit(3 * MINUTE_IN_SECONDS); | |
| 1289 | - | |
| 1290 | - $handler_started = microtime(true); | |
| 1291 | - | |
| 1292 | - $chat = $this->get_param('chat'); | |
| 1293 | - $session_id = $this->get_param('session_id'); | |
| 1294 | - $ai_page_ids = $this->get_param('ai_page_ids', [], null); | |
| 1295 | - // Conversation context, so reopening "Build with AI" later can resume this | |
| 1296 | - // app-end session instead of starting from scratch. `detected_info` is | |
| 1297 | - // sanitized field-by-field in AIUtils::map_chat_detected_info(). | |
| 1298 | - $pack_id = $this->get_param('pack_id', 0, 'absint'); | |
| 1299 | - $platform = $this->get_param('platform'); | |
| 1300 | - $detected_info = $this->get_param('detected_info', [], null); | |
| 1301 | - | |
| 1302 | - if (empty($chat)) { | |
| 1303 | - return $this->error('invalid_chat_id', __('Invalid conversation ID.', 'templately'), 'ai-content/chatbot-import-prepare', 400); | |
| 1304 | - } | |
| 1305 | - | |
| 1306 | - if (empty($session_id)) { | |
| 1307 | - return $this->error('invalid_session_id', __('Invalid session ID.', 'templately'), 'ai-content/chatbot-import-prepare', 400); | |
| 1308 | - } | |
| 1309 | - | |
| 1310 | - // Security: sanitize the session id before it is used to build file paths. | |
| 1311 | - $session_id = AIUtils::sanitize_path_component($session_id, 'session_id'); | |
| 1312 | - if (is_wp_error($session_id)) { | |
| 1313 | - return $this->error('invalid_session_id', $session_id->get_error_message(), 'ai-content/chatbot-import-prepare', 400); | |
| 1314 | - } | |
| 1315 | - | |
| 1316 | - // ai_page_ids may arrive as a JSON string when sent via FormData, and with | |
| 1317 | - // scalar / comma-separated group values — normalize to the canonical | |
| 1318 | - // `type/sub_type => ['id',...]` shape before anything indexes into it. | |
| 1319 | - $ai_page_ids = AIUtils::normalize_ai_page_ids($ai_page_ids); | |
| 1320 | - if (empty($ai_page_ids)) { | |
| 1321 | - return $this->error('invalid_ai_page_ids', __('Invalid AI page IDs.', 'templately'), 'ai-content/chatbot-import-prepare', 400); | |
| 1322 | - } | |
| 1323 | - | |
| 1324 | - // Expected page ids (flattened) — the client may redirect to customization | |
| 1325 | - // as soon as the home/header/footer are ready, so by import time some pages | |
| 1326 | - // can still be generating. We re-pull until every expected page is present | |
| 1327 | - // (bounded wait), then proceed; anything still missing falls back to the | |
| 1328 | - // pack's default content. | |
| 1329 | - $expected_ids = AIUtils::flatten_ai_page_ids($ai_page_ids); | |
| 1330 | - | |
| 1331 | - $extra_headers = ['Accept' => 'application/json']; | |
| 1332 | - $cache_key = self::GENERATED_CACHE_KEY . $chat; | |
| 1333 | - | |
| 1334 | - // This endpoint NEVER waits for completeness. The import starts as soon as | |
| 1335 | - // the session exists; whatever pages are already generated are written | |
| 1336 | - // here as a warm start, and any page still generating is pulled on demand | |
| 1337 | - // by the Finalizer (Core/Importer/Utils/AIContentResolver + | |
| 1338 | - // Providers/ChatAIContentProvider). | |
| 1339 | - // | |
| 1340 | - // Reuse the bundle chatbot-generated just parked, but ONLY when it already | |
| 1341 | - // holds every expected page — a complete bundle cannot become less | |
| 1342 | - // complete, whereas an incomplete one has to be re-pulled to pick up the | |
| 1343 | - // pages that have since finished. On the common handoff (generation | |
| 1344 | - // finished long before the user landed here) this removes an entire | |
| 1345 | - // duplicate transfer of every page's block JSON. | |
| 1346 | - $pull_started = microtime(true); | |
| 1347 | - $pull_duration = 0; | |
| 1348 | - $data = Database::get_transient($cache_key); | |
| 1349 | - $from_cache = is_array($data) && $this->is_generated_bundle_complete($data, $expected_ids); | |
| 1350 | - | |
| 1351 | - if (! $from_cache) { | |
| 1352 | - // Single pull — no server-side sleep/retry. The user can reach import as | |
| 1353 | - // soon as the key pages (home/header/footer) are ready while the rest are | |
| 1354 | - // still generating; rather than hold the request open until everything is | |
| 1355 | - // done (which tripped a gateway 504), we return a non-fatal `pending` | |
| 1356 | - // status and let the client poll (JS-side pull). | |
| 1357 | - $response = Helper::make_api_get_request("v2/chatbot/generated/{$chat}", [], $extra_headers, 2 * MINUTE_IN_SECONDS); | |
| 1358 | - $pull_duration = microtime(true) - $pull_started; | |
| 1359 | - | |
| 1360 | - if (is_wp_error($response)) { | |
| 1361 | - Helper::log(sprintf('chatbot_import_prepare[%s] pull failed after %.2fs: %s', $chat, $pull_duration, $response->get_error_message()), 'ai-import', 'error'); | |
| 1362 | - return $this->error('request_failed', __('Failed to fetch generated content.', 'templately'), 'ai-content/chatbot-import-prepare', 500, ['error_detail' => $response->get_error_message()]); | |
| 1363 | - } | |
| 1364 | - | |
| 1365 | - $response_code = wp_remote_retrieve_response_code($response); | |
| 1366 | - $data = json_decode(wp_remote_retrieve_body($response), true); | |
| 1367 | - | |
| 1368 | - if ($response_code !== 200 || !is_array($data) || !isset($data['status'])) { | |
| 1369 | - $message = (is_array($data) && !empty($data['message'])) ? $data['message'] : sprintf(__('API returned HTTP %d error.', 'templately'), $response_code); | |
| 1370 | - Helper::log(sprintf('chatbot_import_prepare[%s] pull HTTP %d after %.2fs', $chat, $response_code, $pull_duration), 'ai-import', 'error'); | |
| 1371 | - return $this->error('api_http_error', $message, 'ai-content/chatbot-import-prepare', $response_code ?: 500); | |
| 1372 | - } | |
| 1373 | - | |
| 1374 | - // Park a complete bundle for the credits re-read on the success screen. | |
| 1375 | - if ($this->is_generated_bundle_complete($data, $expected_ids)) { | |
| 1376 | - Database::set_transient($cache_key, $data, self::GENERATED_CACHE_TTL); | |
| 1377 | - } | |
| 1378 | - } else { | |
| 1379 | - Helper::log(sprintf('chatbot_import_prepare[%s] reused cached bundle (no upstream pull)', $chat), 'ai-import', 'info'); | |
| 1380 | - } | |
| 1381 | - | |
| 1382 | - $generated = isset($data['data']) && is_array($data['data']) ? $data['data'] : []; | |
| 1383 | - | |
| 1384 | - // Access gate: the backend blocks a free user past their 7-day window. | |
| 1385 | - if (isset($generated['can_import']) && ! $generated['can_import']) { | |
| 1386 | - return $this->error('access_expired', __('Your free access to this generated site has ended. Upgrade your plan or purchase this template to import it.', 'templately'), 'ai-content/chatbot-import-prepare', 403); | |
| 1387 | - } | |
| 1388 | - | |
| 1389 | - $templates = isset($generated['templates']) && is_array($generated['templates']) ? $generated['templates'] : []; | |
| 1390 | - | |
| 1391 | - // Pages the backend skipped (empty source JSON) or failed to generate. | |
| 1392 | - // These will never appear in `templates`, so they must not be treated | |
| 1393 | - // as "still generating" — without this, one skipped page keeps the poll | |
| 1394 | - // pending until it times out. | |
| 1395 | - $skipped_pages = isset($generated['skipped_pages']) && is_array($generated['skipped_pages']) ? array_map('strval', $generated['skipped_pages']) : []; | |
| 1396 | - $skipped_expected = array_values(array_intersect($expected_ids, $skipped_pages)); | |
| 1397 | - | |
| 1398 | - // Which expected pages are still missing from the bundle? | |
| 1399 | - $missing = array_values(array_filter($expected_ids, function ($id) use ($templates, $skipped_pages) { | |
| 1400 | - return !array_key_exists($id, $templates) && !array_key_exists((int) $id, $templates) && !in_array($id, $skipped_pages, true); | |
| 1401 | - })); | |
| 1402 | - | |
| 1403 | - $ready = array_values(array_diff($expected_ids, $missing)); | |
| 1404 | - Helper::log(sprintf('chatbot_import_prepare[%s] warm start: ready=%d/%d missing=%d skipped=%d pull=%.2fs', $chat, count($ready), count($expected_ids), count($missing), count($skipped_expected), $pull_duration), 'ai-import', 'info'); | |
| 1405 | - | |
| 1406 | - | |
| 1407 | - // Derive a process_id for this chat-driven import and register process data | |
| 1408 | - // so the existing validation/ai_get_json paths keep functioning. | |
| 1409 | - $process_id = 'chat-' . $session_id; | |
| 1410 | - $user = $this->utils('options')->get('user'); | |
| 1411 | - | |
| 1412 | - $ai_process_data = AIUtils::get_ai_process_data(); | |
| 1413 | - $record = [ | |
| 1414 | - 'process_id' => $process_id, | |
| 1415 | - 'session_id' => $session_id, | |
| 1416 | - 'ai_page_ids' => $ai_page_ids, | |
| 1417 | - 'api_key' => $this->api_key, | |
| 1418 | - 'user_id' => isset($user['id']) ? $user['id'] : null, | |
| 1419 | - 'chat_id' => $chat, | |
| 1420 | - ]; | |
| 1421 | - | |
| 1422 | - if (!empty($pack_id)) { | |
| 1423 | - $record['pack_id'] = $pack_id; | |
| 1424 | - } | |
| 1425 | - if (!empty($platform)) { | |
| 1426 | - $record['platform'] = $platform; | |
| 1427 | - } | |
| 1428 | - | |
| 1429 | - // Persist the app-end answers exactly as an in-plugin conversation stores | |
| 1430 | - // them, so reopening "Build with AI" resumes this session instead of | |
| 1431 | - // starting over. Without this the record holds no answers at all and the | |
| 1432 | - // sidebar has nothing to restore. | |
| 1433 | - $conversation = AIUtils::build_conversation_fields( | |
| 1434 | - $this->resolve_chat_conversation_fields($chat, $detected_info, $ai_process_data, $process_id) | |
| 1435 | - ); | |
| 1436 | - if (!empty($conversation)) { | |
| 1437 | - $record = array_merge($record, $conversation); | |
| 1438 | - } | |
| 1439 | - | |
| 1440 | - $ai_process_data[$process_id] = $record; | |
| 1441 | - AIUtils::update_ai_process_data($ai_process_data); | |
| 1442 | - | |
| 1443 | - // Persist each generated page to its .ai.json location for the import runners. | |
| 1444 | - // | |
| 1445 | - // Every page present in THIS pull is written immediately, even when others | |
| 1446 | - // are still generating. Holding the writes back until the whole set was | |
| 1447 | - // ready meant a single slow page threw away the full bundle on every poll | |
| 1448 | - // — dozens of multi-hundred-KB pulls (all of `templates`, straight off GCP) | |
| 1449 | - // discarded to save nothing. Writing as we go also lets the Finalizer | |
| 1450 | - // runner finalize the pages that ARE ready instead of blocking on all of | |
| 1451 | - // them. Already-written pages are skipped, so a re-poll is cheap. | |
| 1452 | - $save_started = microtime(true); | |
| 1453 | - $saved_count = 0; | |
| 1454 | - $errors = []; | |
| 1455 | - $processed_pages = get_option('templately_ai_processed_pages', []); | |
| 1456 | - $already_saved = isset($processed_pages[$process_id]['pages']) ? $processed_pages[$process_id]['pages'] : []; | |
| 1457 | - foreach ($templates as $content_id => $template) { | |
| 1458 | - if (empty($template)) { | |
| 1459 | - continue; | |
| 1460 | - } | |
| 1461 | - | |
| 1462 | - if (array_key_exists((string) $content_id, $already_saved)) { | |
| 1463 | - $saved_count++; | |
| 1464 | - continue; | |
| 1465 | - } | |
| 1466 | - | |
| 1467 | - // The runners read JSON strings; normalize arrays/objects to a string. | |
| 1468 | - $template_payload = is_string($template) ? $template : wp_json_encode($template); | |
| 1469 | - | |
| 1470 | - $result = AIUtils::save_template_to_file( | |
| 1471 | - $process_id, | |
| 1472 | - $session_id, | |
| 1473 | - $content_id, | |
| 1474 | - $template_payload, | |
| 1475 | - $ai_page_ids, | |
| 1476 | - false | |
| 1477 | - ); | |
| 1478 | - | |
| 1479 | - if (is_wp_error($result)) { | |
| 1480 | - $errors[$content_id] = $result->get_error_message(); | |
| 1481 | - continue; | |
| 1482 | - } | |
| 1483 | - if (isset($result['status']) && $result['status'] === 'success') { | |
| 1484 | - $saved_count++; | |
| 1485 | - } else { | |
| 1486 | - $errors[$content_id] = isset($result['message']) ? $result['message'] : 'unknown'; | |
| 1487 | - } | |
| 1488 | - } | |
| 1489 | - | |
| 1490 | - // Write each backend-skipped page as an explicit `{"isSkipped": true}` | |
| 1491 | - // marker (same shape the legacy per-page callback wrote) so the import | |
| 1492 | - // runners fall back to the pack's default content instead of treating | |
| 1493 | - // the page as missing. | |
| 1494 | - $skipped_saved = []; | |
| 1495 | - foreach ($skipped_expected as $skipped_id) { | |
| 1496 | - if (array_key_exists($skipped_id, $templates) || array_key_exists((int) $skipped_id, $templates)) { | |
| 1497 | - continue; | |
| 1498 | - } | |
| 1499 | - | |
| 1500 | - if (array_key_exists((string) $skipped_id, $already_saved)) { | |
| 1501 | - $skipped_saved[] = $skipped_id; | |
| 1502 | - continue; | |
| 1503 | - } | |
| 1504 | - | |
| 1505 | - $result = AIUtils::save_template_to_file( | |
| 1506 | - $process_id, | |
| 1507 | - $session_id, | |
| 1508 | - $skipped_id, | |
| 1509 | - '', | |
| 1510 | - $ai_page_ids, | |
| 1511 | - true | |
| 1512 | - ); | |
| 1513 | - | |
| 1514 | - if (is_wp_error($result)) { | |
| 1515 | - $errors[$skipped_id] = $result->get_error_message(); | |
| 1516 | - continue; | |
| 1517 | - } | |
| 1518 | - if (isset($result['status']) && $result['status'] === 'success') { | |
| 1519 | - $skipped_saved[] = $skipped_id; | |
| 1520 | - } else { | |
| 1521 | - $errors[$skipped_id] = isset($result['message']) ? $result['message'] : 'unknown'; | |
| 1522 | - } | |
| 1523 | - } | |
| 1524 | - | |
| 1525 | - $save_duration = microtime(true) - $save_started; | |
| 1526 | - Helper::log(sprintf('chatbot_import_prepare[%s] saved %d/%d pages in %.2fs (skipped=%d, errors=%d)', $chat, $saved_count, count($templates), $save_duration, count($skipped_saved), count($errors)), 'ai-import', 'info'); | |
| 1527 | - | |
| 1528 | - // NOTE: there is deliberately NO `pending` return here any more. Pages that | |
| 1529 | - // are still generating come back in `missing` and are pulled on demand — | |
| 1530 | - // and waited for — by the Finalizer. Returning `pending` made the client | |
| 1531 | - // poll for minutes before the import could even start. | |
| 1532 | - // | |
| 1533 | - // NOT an error when nothing was saved: with the wait deferred to the | |
| 1534 | - // Finalizer it is legitimate for zero pages to be ready at import start. | |
| 1535 | - // Only a genuine write failure (something was ready but every save | |
| 1536 | - // errored) is fatal. | |
| 1537 | - if ($saved_count === 0 && empty($skipped_saved) && !empty($errors)) { | |
| 1538 | - return $this->error('save_failed', __('Failed to save generated content.', 'templately'), 'ai-content/chatbot-import-prepare', 500, ['errors' => $errors]); | |
| 1539 | - } | |
| 1540 | - | |
| 1541 | - Helper::log(sprintf('chatbot_import_prepare[%s] returning: pages=%d missing=%d pull=%.2fs', $chat, count($templates), count($missing), $pull_duration), 'ai-import', 'info'); | |
| 1542 | - | |
| 1543 | - // Import the logo into the media library and map it into the customization. | |
| 1544 | - $customization = isset($generated['customization_data']) && is_array($generated['customization_data']) ? $generated['customization_data'] : []; | |
| 1545 | - $logo = null; | |
| 1546 | - $logo_url = !empty($generated['logo_url']) ? esc_url_raw($generated['logo_url']) : ''; | |
| 1547 | - | |
| 1548 | - if (!empty($logo_url)) { | |
| 1549 | - $logo_started = microtime(true); | |
| 1550 | - $uploaded = Utils::upload_logo($logo_url, $session_id); | |
| 1551 | - Helper::log(sprintf('chatbot_import_prepare[%s] logo upload in %.2fs', $chat, microtime(true) - $logo_started), 'ai-import', 'info'); | |
| 1552 | - if (!empty($uploaded['id'])) { | |
| 1553 | - $logo = [ | |
| 1554 | - 'id' => (int) $uploaded['id'], | |
| 1555 | - 'url' => $uploaded['url'], | |
| 1556 | - ]; | |
| 1557 | - } elseif (!empty($uploaded['error'])) { | |
| 1558 | - // Logo is non-fatal: log and continue without it. | |
| 1559 | - Helper::log('chatbot_import_prepare logo upload failed: ' . $uploaded['error']); | |
| 1560 | - } | |
| 1561 | - } | |
| 1562 | - | |
| 1563 | - // Reflect the imported logo back into the customization payload so React | |
| 1564 | - // can build the settings FormData from a single source. | |
| 1565 | - if (!empty($logo)) { | |
| 1566 | - $customization['logo'] = $logo; | |
| 1567 | - } | |
| 1568 | - | |
| 1569 | - Helper::log(sprintf('chatbot_import_prepare[%s] done in %.2fs total', $chat, microtime(true) - $handler_started), 'ai-import', 'info'); | |
| 1570 | - | |
| 1571 | - return [ | |
| 1572 | - 'status' => 'success', | |
| 1573 | - 'data' => [ | |
| 1574 | - 'session_id' => $session_id, | |
| 1575 | - 'process_id' => $process_id, | |
| 1576 | - 'ai_page_ids' => $ai_page_ids, | |
| 1577 | - 'saved' => $saved_count, | |
| 1578 | - // Pages the backend explicitly skipped — imported with the | |
| 1579 | - // pack's default content instead. | |
| 1580 | - 'skipped' => $skipped_expected, | |
| 1581 | - // Readiness snapshot at import start. `missing` pages are NOT a | |
| 1582 | - // failure: the Finalizer pulls each on demand and waits for it. | |
| 1583 | - 'expected' => $expected_ids, | |
| 1584 | - 'ready' => $ready, | |
| 1585 | - 'missing' => $missing, | |
| 1586 | - 'platform' => isset($customization['platform']) ? $customization['platform'] : null, | |
| 1587 | - 'customization_data' => $customization, | |
| 1588 | - 'logo' => $logo, | |
| 1589 | - 'errors' => $errors, | |
| 1590 | - ], | |
| 1591 | - ]; | |
| 1592 | - } | |
| 1593 | - | |
| 1594 | - /** | |
| 1595 | - * Validate API key against database | |
| 1596 | - * Checks if the provided API key exists for any user on the current site | |
| 1597 | - * Handles both single-site and multisite WordPress installations | |
| 1598 | - * | |
| 1599 | - * @param string $api_key The API key to validate | |
| 1600 | - * @return bool True if valid, false otherwise | |
| 1601 | - */ | |
| 1602 | - private function validate_api_key_in_db($api_key) { | |
| 1603 | - global $wpdb; | |
| 1604 | - | |
| 1605 | - $api_key = sanitize_text_field($api_key); | |
| 1606 | - | |
| 1607 | - if (empty($api_key)) { | |
| 1608 | - return false; | |
| 1609 | - } | |
| 1610 | - | |
| 1611 | - $meta_key = '_templately_api_key'; | |
| 1612 | - | |
| 1613 | - // Handle multisite: key will have site prefix in multisite | |
| 1614 | - if (is_multisite()) { | |
| 1615 | - // get_user_option() uses the format: {$wpdb->base_prefix}{$blog_id}_{$meta_key} | |
| 1616 | - // For current blog, we need to check with the current blog prefix | |
| 1617 | - $blog_id = get_current_blog_id(); | |
| 1618 | - $meta_key = $wpdb->get_blog_prefix($blog_id) . $meta_key; | |
| 1619 | - } | |
| 1620 | - | |
| 1621 | - // Query to check if this API key exists for any user | |
| 1622 | - $query = $wpdb->prepare( | |
| 1623 | - "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value = %s LIMIT 1", | |
| 1624 | - $meta_key, | |
| 1625 | - $api_key | |
| 1626 | - ); | |
| 1627 | - | |
| 1628 | - $user_id = $wpdb->get_var($query); | |
| 1629 | - | |
| 1630 | - return !empty($user_id); | |
| 1631 | 790 | } |
| 1632 | 791 | } |