PluginProbe
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! / 3.7.0
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! v3.7.0
3.7.5 3.7.4 3.7.3 3.7.2 1-final 3.7.1 3.7.0 3.6.8 3.6.7 3.6.6 3.6.5 3.6.4 3.6.3 3.6.2 3.6.1 3.0.3 3.0.4 3.0.5 3.0.6 3.0.7 3.0.8 3.0.9 3.1.0 3.1.1 3.1.10 All 111 releases
templately / includes / API / AIContent.php

AIContent.php in Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! 3.7.0, at includes/API/AIContent.php

1,562 lines 56.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 /**
4 * Templately AI Content Importer
5 *
6 * @package Templately
7 * @since 1.0.0
8 */
9
10 namespace Templately\API;
11
12 use Error;
13 use Exception;
14 use Templately\Utils\Helper;
15 use Templately\Utils\Database;
16 use WP_REST_Request;
17 use WP_Error;
18 use Templately\Core\Importer\Utils\Utils;
19 use Templately\Core\Importer\Utils\AIUtils;
20 use Templately\Core\Importer\Utils\SignatureVerifier;
21 use Templately\Core\Importer\Parsers\WXR_Parser;
22
23 class AIContent extends API {
24 private $endpoint = 'ai-content';
25 private $dev_mode = false;
26
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
40
41 /**
42 * AIContent constructor.
43 *
44 * @param string $file File path.
45 * @param array $settings Settings.
46 */
47 public function __construct() {
48
49 parent::__construct();
50
51 }
52
53 public function _permission_check(WP_REST_Request $request) {
54 $this->request = $request;
55 $this->api_key = $this->utils('options')->get( 'api_key' );
56 $process_id = $this->get_param('process_id');
57
58 $_route = $request->get_route();
59 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 if (empty($process_id)) {
66 return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'calculate_credit', 400);
67 }
68
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 // Check AI process data using API key-based storage
85 $ai_process_data = AIUtils::get_ai_process_data();
86 if (is_array($ai_process_data) && !empty($ai_process_data[$process_id])) {
87 return true;
88 }
89
90 return (bool) AIUtils::get_matched_session_data($process_id);
91 }
92
93 // // Allow access to attachments endpoint
94 // if ('/templately/v1/ai-content/attachments' === $_route) {
95 // return true;
96 // }
97 return parent::_permission_check($request);
98 }
99
100
101 public function register_routes() {
102 // $this->get( $this->endpoint . '/calculate-credit', [ $this, 'calculate_credit' ] );
103 $this->post($this->endpoint . '/modify-content', [$this, 'modify_content']);
104 $this->post($this->endpoint . '/ai-update', [$this, 'ai_update']);
105 $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 $this->get($this->endpoint . '/attachments', [$this, 'get_attachments'], [
145 'type' => [
146 'default' => 'pack',
147 'required' => false,
148 'sanitize_callback' => 'sanitize_text_field',
149 ],
150 'id' => [
151 'required' => false,
152 'sanitize_callback' => 'sanitize_text_field',
153 ],
154 'pack_id' => [
155 'required' => false,
156 'sanitize_callback' => 'sanitize_text_field',
157 ],
158 ]);
159 $this->get($this->endpoint . '/images', [$this, 'search_images'], [
160 'query' => [
161 'required' => false,
162 'sanitize_callback' => 'sanitize_text_field',
163 'validate_callback' => function($param, $request, $key) {
164 return is_string($param) && strlen($param) <= 255;
165 },
166 ],
167 'orientation' => [
168 'required' => false,
169 'default' => 'all',
170 'sanitize_callback' => 'sanitize_text_field',
171 'validate_callback' => function($param, $request, $key) {
172 $allowed_orientations = ['all', 'landscape', 'portrait', 'square'];
173 return in_array($param, $allowed_orientations, true);
174 },
175 ],
176 'size' => [
177 'required' => false,
178 'default' => 'medium',
179 'sanitize_callback' => 'sanitize_text_field',
180 'validate_callback' => function($param, $request, $key) {
181 $allowed_sizes = ['small', 'medium', 'large'];
182 return in_array($param, $allowed_sizes, true);
183 },
184 ],
185 'color' => [
186 'required' => false,
187 'sanitize_callback' => 'sanitize_text_field',
188 'validate_callback' => function($param, $request, $key) {
189 return is_string($param) && strlen($param) <= 50;
190 },
191 ],
192 'page' => [
193 'required' => false,
194 'default' => 1,
195 'sanitize_callback' => 'absint',
196 'validate_callback' => function($param, $request, $key) {
197 return is_numeric($param) && $param > 0 && $param <= 1000;
198 },
199 ],
200 'per_page' => [
201 'required' => false,
202 'default' => 20,
203 'sanitize_callback' => 'absint',
204 'validate_callback' => function($param, $request, $key) {
205 return is_numeric($param) && $param > 0 && $param <= 100;
206 },
207 ],
208 ]);
209 // die(rest_url( 'templately/v1/ai-content/ai-update' ));
210 }
211
212 public function calculate_credit() {
213 $pack_id = $this->get_param('pack_id');
214
215 return [
216 'status' => 'success',
217 'data' => [
218 'availableCredit' => 100,
219 ],
220 ];
221
222 if (empty($pack_id)) {
223 return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'calculate_credit', 400);
224 }
225
226 $extra_headers = [
227 'Accept' => 'application/json',
228 ];
229 $response = Helper::make_api_get_request("v2/ai/calculate-credit/pack/$pack_id", [], $extra_headers, 30);
230
231
232 // return $response;
233 if (is_wp_error($response)) {
234 return $this->error('request_failed', __('Request failed.', 'templately'), 'calculate_credit', 500, ['error_detail' => $response->get_error_message()]);
235 }
236
237 $body = wp_remote_retrieve_body($response);
238 $data = json_decode($body, true);
239 // error status is ok
240 if (! is_array($data) || ! isset($data['status'])) {
241 return $this->error('invalid_response', __('Invalid response.', 'templately'), 'calculate_credit', 500);
242 }
243
244
245 return $data;
246 }
247
248 public function modify_content() {
249 add_filter('wp_redirect', '__return_false', 999);
250 set_time_limit(3 * MINUTE_IN_SECONDS);
251 ini_set('max_execution_time', 3 * MINUTE_IN_SECONDS);
252
253 $pack_id = $this->get_param('pack_id');
254 $isBusinessNichesNew = $this->get_param('isBusinessNichesNew', false);
255 $ai_page_ids = $this->get_param('ai_page_ids', [], null);
256 $content_ids = $this->get_param('content_ids', [], null);
257 $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 $preview_pages = $this->get_param('preview_pages', [], null);
268 $image_replace = $this->get_param('imageReplace', [], null);
269 $platform = $this->get_param('platform');
270 $language = $this->get_param('language', null);
271
272 // 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');
281
282 if (empty($pack_id)) {
283 return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'modify_content', 400);
284 }
285 if (empty($category)) {
286 return $this->error('invalid_prompt', __('Invalid prompt.', 'templately'), 'modify_content', 400);
287 }
288 if (empty($content_ids) && empty($preview_pages)) {
289 return $this->error('invalid_content_ids', __('Invalid content ids.', 'templately'), 'modify_content', 400);
290 }
291 if (empty($platform)) {
292 return $this->error('invalid_platform', __('Invalid platform.', 'templately'), 'modify_content', 400);
293 }
294
295
296 // $response = get_transient( '__templately_ai_process_id' );
297
298 // if(empty($response)) {
299 $extra_headers = [
300 'Accept' => 'application/json',
301 'x-templately-session-id' => $session_id,
302 'x-templately-requested-platform' => $requested_platform,
303 ];
304 $body_data = [
305 'business_name' => $name,
306 'business_niches' => $category,
307 'prompt' => $description,
308 'email' => $email,
309 'phone' => $contactNumber,
310 'address' => $businessAddress,
311 'openingHour' => $openingHour,
312 'pack_id' => $pack_id,
313 'content_ids' => $content_ids,
314 'platform' => $platform,
315 'preview_pages' => $preview_pages,
316 'language' => $language,
317 'callback' => defined('TEMPLATELY_CALLBACK') ? TEMPLATELY_CALLBACK . '/wp-json/templately/v1/ai-content/ai-update' : rest_url('templately/v1/ai-content/ai-update'),
318 ];
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 $response = Helper::make_api_post_request('v2/ai/modify-content/pack', $body_data, $extra_headers, 15 * MINUTE_IN_SECONDS);
329
330 // set_transient( '__templately_ai_process_id', $response, 60 * 60 * 24 * 30 );
331 // }
332
333 $bk_ai_business_niches = get_option('templately_ai_business_niches', []);
334 if (!empty($business_niches) && $isBusinessNichesNew && ! in_array($business_niches, $bk_ai_business_niches)) {
335 $bk_ai_business_niches[] = $business_niches;
336 update_option('templately_ai_business_niches', $bk_ai_business_niches, false);
337 }
338
339 // return $response;
340 if (is_wp_error($response)) {
341 error_log(print_r($response, true));
342 return $this->error('request_failed', __('Request failed.', 'templately'), 'modify_content', 500, ['error_data' => $response->get_error_data()]);
343 }
344
345 $body = wp_remote_retrieve_body($response);
346 $data = json_decode($body, true);
347 // error status is ok, if status is error then return as is
348 if (! is_array($data) || ! isset($data['status'])) {
349 return $this->error('invalid_response', __('Invalid response.', 'templately'), 'modify_content', 500, ['data' => $data]);
350 }
351
352 // "{"status":"success","message":"The content is being generated in the queue","process_id":"01JRQQD39GNWTNF18EWF8YH0BG-271838-pack-408"}"
353 if (isset($data['status']) && $data['status'] === 'success' && isset($data['process_id'])) {
354 $process_id = $data['process_id'];
355
356 // // Save templates to files if available using the common function
357 // if (!empty($data['templates']) && is_array($data['templates'])) {
358 // foreach ($data['templates'] as $content_id => $template_data) {
359 // // Decode template if it's base64 encoded
360 // if (! empty($template_data) && base64_decode($template_data, true) !== false) {
361 // $data['templates'][$content_id] = base64_decode($template_data);
362 // }
363
364 // if (!empty($template_data)) {
365 // AIUtils::save_template_to_file(
366 // $process_id,
367 // $content_id,
368 // $template_data,
369 // $ai_page_ids,
370 // true, // Always use preview mode for AI content workflow
371 // isset($template_data['isSkipped']) ? $template_data['isSkipped'] : false
372 // );
373 // }
374 // }
375 // }
376
377 $user = $this->utils('options')->get('user');
378
379 $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,
399 ];
400
401 // Update using API key-based storage with automatic count-based cleanup
402 AIUtils::update_ai_process_data($ai_process_data);
403
404 return [
405 'status' => 'success',
406 'message' => __('The content is being generated in the queue', 'templately'),
407 'process_id' => $process_id,
408 'templates' => !empty($data['templates']) ? $data['templates'] : null,
409 'is_local_site' => !empty($data['is_local_site']) ? $data['is_local_site'] : null,
410 ];
411 }
412
413 return $data;
414 }
415
416 public function ai_update() {
417 add_filter('wp_redirect', '__return_false', 999);
418
419 $template = $this->get_param('template');
420 $process_id = $this->get_param('process_id');
421 $template_id = $this->get_param('template_id');
422 $content_id = $this->get_param('content_id');
423 $type = $this->get_param('type');
424 $isSkipped = $this->get_param('isSkipped', false);
425 $credit_cost = $this->request->get_param('credit_cost');
426
427 error_log('process_id: ' . $process_id);
428
429 // Handle credit cost updates separately
430 if ($this->request->has_param('credit_cost')) {
431 $processed_pages = get_option("templately_ai_processed_pages", []);
432 $processed_pages[$process_id] = $processed_pages[$process_id] ?? [];
433 $processed_pages[$process_id]['credit_cost'] = $credit_cost;
434 update_option("templately_ai_processed_pages", $processed_pages, false);
435
436 return [
437 'status' => 'success',
438 'data' => [
439 'process_id' => $process_id,
440 'credit_cost' => $credit_cost,
441 ],
442 ];
443 }
444
445 // Always use preview mode for AI content workflow
446 // Validate and get process data using centralized method
447 $process_data = AIUtils::validate_and_get_process_data($process_id);
448 if (is_wp_error($process_data)) {
449 return $process_data;
450 }
451
452 $session_id = $process_data['session_id'];
453 $ai_page_ids = $process_data['ai_page_ids'];
454
455 // Use the common helper function to save the template
456 $result = AIUtils::save_template_to_file(
457 $process_id,
458 $session_id,
459 $content_id,
460 $template,
461 $ai_page_ids,
462 $isSkipped
463 );
464
465 if(is_wp_error($result)){
466 return $result;
467 }
468
469 // Return the result from the helper function
470 if (isset($result['status']) && $result['status'] === 'success') {
471 return $result;
472 }
473
474 // Return error if the helper function failed
475 return $result;
476 }
477
478 public function ai_update_preview() {
479 add_filter('wp_redirect', '__return_false', 999);
480
481 $template = $this->get_param('templates'); // Now expects an array with content_id as keys
482 $process_id = $this->get_param('process_id');
483 $isSkipped = $this->get_param('isSkipped', false);
484 $error = $this->get_param('error', null);
485
486 error_log('process_id: ' . $process_id);
487
488 if (!empty($isSkipped) || !empty($error)) {
489 // Update AI process data with error using API key-based storage
490 $ai_process_data = AIUtils::get_ai_process_data();
491 if (isset($ai_process_data[$process_id])) {
492 $ai_process_data[$process_id]['preview_error'] = $error;
493 AIUtils::update_ai_process_data($ai_process_data);
494 }
495 wp_send_json_error([
496 'status' => 'error',
497 'message' => $error,
498 ]);
499 }
500
501 // Validate template parameter is an array
502 if (!is_array($template) || empty($template)) {
503 return $this->error('invalid_template', __('Template must be a non-empty array with content_id as keys.', 'templately'), 'ai-content/ai-update-preview', 400);
504 }
505
506 // Always use preview mode for AI content workflow
507 // Validate and get process data using centralized method
508 $process_data = AIUtils::validate_and_get_process_data($process_id);
509 if (is_wp_error($process_data)) {
510 return $process_data;
511 }
512
513 $session_id = $process_data['session_id'];
514 $ai_page_ids = $process_data['ai_page_ids'];
515 $results = [];
516 $success_count = 0;
517 $error_count = 0;
518
519 // Process each content_id/template pair
520 foreach ($template as $content_id => $template_data) {
521 // Use the common helper function to save the template (always preview mode)
522 $result = AIUtils::save_template_to_file(
523 $process_id,
524 $session_id,
525 $content_id,
526 $template_data,
527 $ai_page_ids,
528 $isSkipped
529 );
530
531 $results[$content_id] = $result;
532
533 // Track success/error counts
534 if (isset($result['status']) && $result['status'] === 'success') {
535 $success_count++;
536 } else {
537 $error_count++;
538 }
539 }
540
541 // Return consolidated response
542 $overall_status = $error_count === 0 ? 'success' : ($success_count === 0 ? 'error' : 'partial_success');
543
544 // Note: No cleanup needed with API key-based storage and count-based management
545
546 return [
547 'status' => $overall_status,
548 'message' => sprintf(
549 __('Processed %d templates: %d successful, %d failed.', 'templately'),
550 count($template),
551 $success_count,
552 $error_count
553 ),
554 ];
555 }
556
557
558
559 /**
560 * Get attachments from API endpoint
561 *
562 * @return array|\WP_Error
563 */
564 public function get_attachments() {
565 // 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');
569
570 // Require ID parameter - return error if not provided
571 if (empty($id)) {
572 return $this->error('missing_id', __('Pack ID or ID parameter is required.', 'templately'), 'get_attachments', 400);
573 }
574
575 try {
576 // Construct API endpoint URL
577 $api_endpoint = "get-xml-attachment/{$type}/{$id}";
578
579 // Make API call
580 $extra_headers = [
581 'Accept' => 'application/xml, text/xml',
582 'x-templately-requested-platform' => $requested_platform,
583 ];
584 $response = Helper::make_api_get_request("v2/$api_endpoint", [], $extra_headers, 30);
585
586 // Check for HTTP errors
587 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()]);
589 }
590
591 $response_code = wp_remote_retrieve_response_code($response);
592 $xml_content = wp_remote_retrieve_body($response);
593
594 if ($response_code !== 200) {
595 // check if $xml_content contains valid json
596 // ex. '{"status":"error","message":"Attachment XML file not found in pack archive."}'
597 $error_data = @json_decode($xml_content, true);
598 if(is_array($error_data) && isset($error_data['status']) && $error_data['status'] === 'error' && !empty($error_data['message'])){
599 return $this->error('api_http_error', $error_data['message'], 'get_attachments', $response_code);
600 }
601 return $this->error('api_http_error', sprintf(__('API returned HTTP %d error.', 'templately'), $response_code), 'get_attachments', $response_code);
602 }
603
604 // Validate we have XML content
605 if (empty($xml_content)) {
606 return $this->error('no_xml_content', __('No XML content found in API response.', 'templately'), 'get_attachments', 404);
607 }
608
609 // Parse the XML content from API response
610 $parsed_data = $this->parse_xml_content($xml_content);
611
612 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()]);
614 }
615
616 // Extract attachments from parsed data
617 $attachments = $this->extract_attachments_from_parsed_data($parsed_data);
618
619 return [
620 'status' => 'success',
621 'data' => $attachments,
622 'message' => sprintf(__('Found %d attachments.', 'templately'), count($attachments)),
623 ];
624
625 } catch (Exception $e) {
626 return $this->error('exception', __('An unexpected error occurred while fetching attachments.', 'templately'), 'get_attachments', 500, ['error_detail' => $e->getMessage()]);
627 }
628 }
629
630
631
632 /**
633 * Parse XML content string using WXR Parser
634 *
635 * @param string $xml_content XML content string
636 * @return array|\WP_Error Parsed data or error
637 */
638 private function parse_xml_content($xml_content) {
639 // Ensure WordPress filesystem functions are available
640 if (!function_exists('wp_tempnam')) {
641 require_once(ABSPATH . 'wp-admin/includes/file.php');
642 }
643
644 // Create a temporary file to store XML content
645 $temp_file = wp_tempnam('templately_attachments');
646 if (!$temp_file) {
647 return new WP_Error('temp_file_failed', __('Failed to create temporary file.', 'templately'));
648 }
649
650 // Write XML content to temporary file
651 $bytes_written = file_put_contents($temp_file, $xml_content);
652 if ($bytes_written === false) {
653 unlink($temp_file);
654 return new WP_Error('write_failed', __('Failed to write XML content to temporary file.', 'templately'));
655 }
656
657 try {
658 // Initialize WXR Parser
659 $parser = new WXR_Parser();
660
661 // Parse the temporary XML file
662 $parsed_data = $parser->parse($temp_file);
663
664 // Clean up temporary file
665 unlink($temp_file);
666
667 return $parsed_data;
668
669 } catch (Exception $e) {
670 // Clean up temporary file on exception
671 if (file_exists($temp_file)) {
672 unlink($temp_file);
673 }
674 return new WP_Error('parse_exception', $e->getMessage());
675 }
676 }
677
678 /**
679 * Extract attachments from parsed WXR data
680 *
681 * @param array $parsed_data Parsed WXR data
682 * @return array Array of attachment data
683 */
684 private function extract_attachments_from_parsed_data($parsed_data) {
685 $attachments = [];
686
687 if (isset($parsed_data['posts']) && is_array($parsed_data['posts'])) {
688 foreach ($parsed_data['posts'] as $post) {
689 // Check if this is an attachment
690 if (isset($post['post_type']) && $post['post_type'] === 'attachment') {
691 $attachment = [
692 'id' => isset($post['post_id']) ? (int) $post['post_id'] : 0,
693 'url' => isset($post['attachment_url']) ? (string) $post['attachment_url'] : '',
694 'title' => isset($post['post_title']) ? (string) $post['post_title'] : '',
695 'type' => isset($post['attachment_type']) ? (string) $post['attachment_type'] : '',
696 ];
697
698 // Extract metadata including dimensions and medium URL
699 $metadata = $this->extract_medium_size_url($post, $attachment['url']);
700
701 // Filter out small images (width or height <= 150px) to ignore small icons
702 if ($metadata && isset($metadata['width']) && isset($metadata['height'])) {
703 if ($metadata['width'] < 150 || $metadata['height'] < 150) {
704 continue; // Skip small images/icons
705 }
706
707 // Add dimensions to attachment data
708 $attachment['width'] = $metadata['width'];
709 $attachment['height'] = $metadata['height'];
710
711 // Add medium URL if available
712 if (isset($metadata['medium_url'])) {
713 $attachment['medium_url'] = $metadata['medium_url'];
714 }
715 } else {
716 // Skip attachments without metadata or dimensions
717 continue;
718 }
719
720 // Only add if we have the required data
721 if ($attachment['id'] && $attachment['url'] && $attachment['title']) {
722 $attachments[] = $attachment;
723 }
724 }
725 }
726 }
727
728 return $attachments;
729 }
730
731 /**
732 * Extract medium size URL from attachment metadata and get image dimensions
733 *
734 * @param array $post Post data from WXR parser
735 * @param string $original_url Original attachment URL
736 * @return array|null Array with medium_url and dimensions if found, null otherwise
737 */
738 private function extract_medium_size_url($post, $original_url) {
739 if (!isset($post['postmeta']) || !is_array($post['postmeta'])) {
740 return null;
741 }
742
743 foreach ($post['postmeta'] as $meta) {
744 if (!isset($meta['key']) || !isset($meta['value'])) {
745 continue;
746 }
747
748 // Only check _wp_attachment_metadata
749 if ($meta['key'] === '_wp_attachment_metadata') {
750 $attachment_metadata = @unserialize($meta['value']);
751 if (is_array($attachment_metadata)) {
752 $result = [];
753
754 // Get original image dimensions
755 $width = isset($attachment_metadata['width']) ? (int) $attachment_metadata['width'] : 0;
756 $height = isset($attachment_metadata['height']) ? (int) $attachment_metadata['height'] : 0;
757
758 $result['width'] = $width;
759 $result['height'] = $height;
760
761 // Check if medium size exists
762 if (isset($attachment_metadata['sizes']['medium']['file'])) {
763 // Construct medium URL from original URL and medium filename
764 $medium_filename = $attachment_metadata['sizes']['medium']['file'];
765 $original_path = dirname(parse_url($original_url, PHP_URL_PATH));
766 $base_url = str_replace(parse_url($original_url, PHP_URL_PATH), '', $original_url);
767 $result['medium_url'] = $base_url . $original_path . '/' . $medium_filename;
768 }
769
770 return $result;
771 }
772 }
773 }
774
775 return null;
776 }
777
778
779
780 /**
781 * Search images endpoint
782 *
783 * @param WP_REST_Request $request
784 * @return WP_REST_Response|WP_Error
785 */
786 public function search_images(WP_REST_Request $request) {
787 // Get and sanitize parameters
788 $query = $this->get_param('query', '');
789 $orientation = $this->get_param('orientation', 'all');
790 $size = $this->get_param('size', 'medium');
791 $color = $this->get_param('color', '');
792 $page = $this->get_param('page', 1, 'absint');
793 $per_page = $this->get_param('per_page', 20, 'absint');
794
795 // Validate required query parameter
796 if (empty($query)) {
797 return $this->error(
798 'missing_query',
799 __('Search query is required.', 'templately'),
800 'search_images',
801 400
802 );
803 }
804
805 // Prepare API request parameters
806 $api_params = [
807 'query' => urlencode($query),
808 'page' => $page,
809 'per_page' => $per_page,
810 ];
811
812 // Add optional parameters if provided
813 if ($orientation !== 'all') {
814 $api_params['orientation'] = $orientation;
815 }
816
817 if (!empty($size)) {
818 $api_params['size'] = $size;
819 }
820
821 if (!empty($color)) {
822 $api_params['color'] = $color;
823 }
824
825 // Make API request to external image service
826 $extra_headers = [
827 'Content-Type' => 'application/json',
828 ];
829
830 $response = Helper::make_api_get_request('v2/images', $api_params, $extra_headers, 30);
831
832 // Handle API response errors
833 if (is_wp_error($response)) {
834 return $this->error(
835 'api_request_failed',
836 __('Failed to fetch images from external service.', 'templately'),
837 'search_images',
838 500
839 );
840 }
841
842 $response_code = wp_remote_retrieve_response_code($response);
843 $response_body = wp_remote_retrieve_body($response);
844
845 if ($response_code !== 200) {
846 return $this->error(
847 'api_response_error',
848 sprintf(__('External API returned error code: %d', 'templately'), $response_code),
849 'search_images',
850 $response_code
851 );
852 }
853
854 // Parse and validate response
855 $data = json_decode($response_body, true);
856 if (json_last_error() !== JSON_ERROR_NONE) {
857 return $this->error(
858 'invalid_response',
859 __('Invalid response from external service.', 'templately'),
860 'search_images',
861 500
862 );
863 }
864
865 // Check if the response has the expected structure and success status
866 if (!isset($data['status']) || $data['status'] !== 'success') {
867 return $this->error(
868 'api_response_error',
869 __('External API returned an error status.', 'templately'),
870 'search_images',
871 500
872 );
873 }
874
875 // Extract nested data from the response
876 $response_data = $data['data'] ?? [];
877 $images = $response_data['images'] ?? [];
878 $total_results = $response_data['total_results'] ?? 0;
879 $current_page = $response_data['page'] ?? $page;
880 $per_page_count = $response_data['per_page'] ?? $per_page;
881
882 // Return successful response with properly mapped data
883 return $this->success([
884 'images' => $images,
885 'total' => $total_results,
886 'page' => $current_page,
887 'per_page' => $per_page_count,
888 'total_pages' => $total_results > 0 ? ceil($total_results / $per_page_count) : 0,
889 ]);
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 public function chatbot_import_prepare() {
1242 add_filter('wp_redirect', '__return_false', 999);
1243 set_time_limit(3 * MINUTE_IN_SECONDS);
1244
1245 $handler_started = microtime(true);
1246
1247 $chat = $this->get_param('chat');
1248 $session_id = $this->get_param('session_id');
1249 $ai_page_ids = $this->get_param('ai_page_ids', [], null);
1250
1251 if (empty($chat)) {
1252 return $this->error('invalid_chat_id', __('Invalid conversation ID.', 'templately'), 'ai-content/chatbot-import-prepare', 400);
1253 }
1254
1255 if (empty($session_id)) {
1256 return $this->error('invalid_session_id', __('Invalid session ID.', 'templately'), 'ai-content/chatbot-import-prepare', 400);
1257 }
1258
1259 // Security: sanitize the session id before it is used to build file paths.
1260 $session_id = AIUtils::sanitize_path_component($session_id, 'session_id');
1261 if (is_wp_error($session_id)) {
1262 return $this->error('invalid_session_id', $session_id->get_error_message(), 'ai-content/chatbot-import-prepare', 400);
1263 }
1264
1265 // ai_page_ids may arrive as a JSON string when sent via FormData, and with
1266 // scalar / comma-separated group values — normalize to the canonical
1267 // `type/sub_type => ['id',...]` shape before anything indexes into it.
1268 $ai_page_ids = AIUtils::normalize_ai_page_ids($ai_page_ids);
1269 if (empty($ai_page_ids)) {
1270 return $this->error('invalid_ai_page_ids', __('Invalid AI page IDs.', 'templately'), 'ai-content/chatbot-import-prepare', 400);
1271 }
1272
1273 // Expected page ids (flattened) — the client may redirect to customization
1274 // as soon as the home/header/footer are ready, so by import time some pages
1275 // can still be generating. We re-pull until every expected page is present
1276 // (bounded wait), then proceed; anything still missing falls back to the
1277 // pack's default content.
1278 $expected_ids = AIUtils::flatten_ai_page_ids($ai_page_ids);
1279
1280 $extra_headers = ['Accept' => 'application/json'];
1281 $cache_key = self::GENERATED_CACHE_KEY . $chat;
1282
1283 // This endpoint NEVER waits for completeness. The import starts as soon as
1284 // the session exists; whatever pages are already generated are written
1285 // here as a warm start, and any page still generating is pulled on demand
1286 // by the Finalizer (Core/Importer/Utils/AIContentResolver +
1287 // Providers/ChatAIContentProvider).
1288 //
1289 // Reuse the bundle chatbot-generated just parked, but ONLY when it already
1290 // holds every expected page — a complete bundle cannot become less
1291 // complete, whereas an incomplete one has to be re-pulled to pick up the
1292 // pages that have since finished. On the common handoff (generation
1293 // finished long before the user landed here) this removes an entire
1294 // duplicate transfer of every page's block JSON.
1295 $pull_started = microtime(true);
1296 $pull_duration = 0;
1297 $data = Database::get_transient($cache_key);
1298 $from_cache = is_array($data) && $this->is_generated_bundle_complete($data, $expected_ids);
1299
1300 if (! $from_cache) {
1301 // Single pull — no server-side sleep/retry. The user can reach import as
1302 // soon as the key pages (home/header/footer) are ready while the rest are
1303 // still generating; rather than hold the request open until everything is
1304 // done (which tripped a gateway 504), we return a non-fatal `pending`
1305 // status and let the client poll (JS-side pull).
1306 $response = Helper::make_api_get_request("v2/chatbot/generated/{$chat}", [], $extra_headers, 2 * MINUTE_IN_SECONDS);
1307 $pull_duration = microtime(true) - $pull_started;
1308
1309 if (is_wp_error($response)) {
1310 Helper::log(sprintf('chatbot_import_prepare[%s] pull failed after %.2fs: %s', $chat, $pull_duration, $response->get_error_message()), 'ai-import', 'error');
1311 return $this->error('request_failed', __('Failed to fetch generated content.', 'templately'), 'ai-content/chatbot-import-prepare', 500, ['error_detail' => $response->get_error_message()]);
1312 }
1313
1314 $response_code = wp_remote_retrieve_response_code($response);
1315 $data = json_decode(wp_remote_retrieve_body($response), true);
1316
1317 if ($response_code !== 200 || !is_array($data) || !isset($data['status'])) {
1318 $message = (is_array($data) && !empty($data['message'])) ? $data['message'] : sprintf(__('API returned HTTP %d error.', 'templately'), $response_code);
1319 Helper::log(sprintf('chatbot_import_prepare[%s] pull HTTP %d after %.2fs', $chat, $response_code, $pull_duration), 'ai-import', 'error');
1320 return $this->error('api_http_error', $message, 'ai-content/chatbot-import-prepare', $response_code ?: 500);
1321 }
1322
1323 // Park a complete bundle for the credits re-read on the success screen.
1324 if ($this->is_generated_bundle_complete($data, $expected_ids)) {
1325 Database::set_transient($cache_key, $data, self::GENERATED_CACHE_TTL);
1326 }
1327 } else {
1328 Helper::log(sprintf('chatbot_import_prepare[%s] reused cached bundle (no upstream pull)', $chat), 'ai-import', 'info');
1329 }
1330
1331 $generated = isset($data['data']) && is_array($data['data']) ? $data['data'] : [];
1332
1333 // Access gate: the backend blocks a free user past their 7-day window.
1334 if (isset($generated['can_import']) && ! $generated['can_import']) {
1335 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);
1336 }
1337
1338 $templates = isset($generated['templates']) && is_array($generated['templates']) ? $generated['templates'] : [];
1339
1340 // Pages the backend skipped (empty source JSON) or failed to generate.
1341 // These will never appear in `templates`, so they must not be treated
1342 // as "still generating" — without this, one skipped page keeps the poll
1343 // pending until it times out.
1344 $skipped_pages = isset($generated['skipped_pages']) && is_array($generated['skipped_pages']) ? array_map('strval', $generated['skipped_pages']) : [];
1345 $skipped_expected = array_values(array_intersect($expected_ids, $skipped_pages));
1346
1347 // Which expected pages are still missing from the bundle?
1348 $missing = array_values(array_filter($expected_ids, function ($id) use ($templates, $skipped_pages) {
1349 return !array_key_exists($id, $templates) && !array_key_exists((int) $id, $templates) && !in_array($id, $skipped_pages, true);
1350 }));
1351
1352 $ready = array_values(array_diff($expected_ids, $missing));
1353 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');
1354
1355
1356 // Derive a process_id for this chat-driven import and register process data
1357 // so the existing validation/ai_get_json paths keep functioning.
1358 $process_id = 'chat-' . $session_id;
1359 $user = $this->utils('options')->get('user');
1360
1361 $ai_process_data = AIUtils::get_ai_process_data();
1362 $ai_process_data[$process_id] = [
1363 'process_id' => $process_id,
1364 'session_id' => $session_id,
1365 'ai_page_ids' => $ai_page_ids,
1366 'api_key' => $this->api_key,
1367 'user_id' => isset($user['id']) ? $user['id'] : null,
1368 'chat_id' => $chat,
1369 ];
1370 AIUtils::update_ai_process_data($ai_process_data);
1371
1372 // Persist each generated page to its .ai.json location for the import runners.
1373 //
1374 // Every page present in THIS pull is written immediately, even when others
1375 // are still generating. Holding the writes back until the whole set was
1376 // ready meant a single slow page threw away the full bundle on every poll
1377 // — dozens of multi-hundred-KB pulls (all of `templates`, straight off GCP)
1378 // discarded to save nothing. Writing as we go also lets the Finalizer
1379 // runner finalize the pages that ARE ready instead of blocking on all of
1380 // them. Already-written pages are skipped, so a re-poll is cheap.
1381 $save_started = microtime(true);
1382 $saved_count = 0;
1383 $errors = [];
1384 $processed_pages = get_option('templately_ai_processed_pages', []);
1385 $already_saved = isset($processed_pages[$process_id]['pages']) ? $processed_pages[$process_id]['pages'] : [];
1386 foreach ($templates as $content_id => $template) {
1387 if (empty($template)) {
1388 continue;
1389 }
1390
1391 if (array_key_exists((string) $content_id, $already_saved)) {
1392 $saved_count++;
1393 continue;
1394 }
1395
1396 // The runners read JSON strings; normalize arrays/objects to a string.
1397 $template_payload = is_string($template) ? $template : wp_json_encode($template);
1398
1399 $result = AIUtils::save_template_to_file(
1400 $process_id,
1401 $session_id,
1402 $content_id,
1403 $template_payload,
1404 $ai_page_ids,
1405 false
1406 );
1407
1408 if (is_wp_error($result)) {
1409 $errors[$content_id] = $result->get_error_message();
1410 continue;
1411 }
1412 if (isset($result['status']) && $result['status'] === 'success') {
1413 $saved_count++;
1414 } else {
1415 $errors[$content_id] = isset($result['message']) ? $result['message'] : 'unknown';
1416 }
1417 }
1418
1419 // Write each backend-skipped page as an explicit `{"isSkipped": true}`
1420 // marker (same shape the legacy per-page callback wrote) so the import
1421 // runners fall back to the pack's default content instead of treating
1422 // the page as missing.
1423 $skipped_saved = [];
1424 foreach ($skipped_expected as $skipped_id) {
1425 if (array_key_exists($skipped_id, $templates) || array_key_exists((int) $skipped_id, $templates)) {
1426 continue;
1427 }
1428
1429 if (array_key_exists((string) $skipped_id, $already_saved)) {
1430 $skipped_saved[] = $skipped_id;
1431 continue;
1432 }
1433
1434 $result = AIUtils::save_template_to_file(
1435 $process_id,
1436 $session_id,
1437 $skipped_id,
1438 '',
1439 $ai_page_ids,
1440 true
1441 );
1442
1443 if (is_wp_error($result)) {
1444 $errors[$skipped_id] = $result->get_error_message();
1445 continue;
1446 }
1447 if (isset($result['status']) && $result['status'] === 'success') {
1448 $skipped_saved[] = $skipped_id;
1449 } else {
1450 $errors[$skipped_id] = isset($result['message']) ? $result['message'] : 'unknown';
1451 }
1452 }
1453
1454 $save_duration = microtime(true) - $save_started;
1455 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');
1456
1457 // NOTE: there is deliberately NO `pending` return here any more. Pages that
1458 // are still generating come back in `missing` and are pulled on demand —
1459 // and waited for — by the Finalizer. Returning `pending` made the client
1460 // poll for minutes before the import could even start.
1461 //
1462 // NOT an error when nothing was saved: with the wait deferred to the
1463 // Finalizer it is legitimate for zero pages to be ready at import start.
1464 // Only a genuine write failure (something was ready but every save
1465 // errored) is fatal.
1466 if ($saved_count === 0 && empty($skipped_saved) && !empty($errors)) {
1467 return $this->error('save_failed', __('Failed to save generated content.', 'templately'), 'ai-content/chatbot-import-prepare', 500, ['errors' => $errors]);
1468 }
1469
1470 Helper::log(sprintf('chatbot_import_prepare[%s] returning: pages=%d missing=%d pull=%.2fs', $chat, count($templates), count($missing), $pull_duration), 'ai-import', 'info');
1471
1472 // Import the logo into the media library and map it into the customization.
1473 $customization = isset($generated['customization_data']) && is_array($generated['customization_data']) ? $generated['customization_data'] : [];
1474 $logo = null;
1475 $logo_url = !empty($generated['logo_url']) ? esc_url_raw($generated['logo_url']) : '';
1476
1477 if (!empty($logo_url)) {
1478 $logo_started = microtime(true);
1479 $uploaded = Utils::upload_logo($logo_url, $session_id);
1480 Helper::log(sprintf('chatbot_import_prepare[%s] logo upload in %.2fs', $chat, microtime(true) - $logo_started), 'ai-import', 'info');
1481 if (!empty($uploaded['id'])) {
1482 $logo = [
1483 'id' => (int) $uploaded['id'],
1484 'url' => $uploaded['url'],
1485 ];
1486 } elseif (!empty($uploaded['error'])) {
1487 // Logo is non-fatal: log and continue without it.
1488 Helper::log('chatbot_import_prepare logo upload failed: ' . $uploaded['error']);
1489 }
1490 }
1491
1492 // Reflect the imported logo back into the customization payload so React
1493 // can build the settings FormData from a single source.
1494 if (!empty($logo)) {
1495 $customization['logo'] = $logo;
1496 }
1497
1498 Helper::log(sprintf('chatbot_import_prepare[%s] done in %.2fs total', $chat, microtime(true) - $handler_started), 'ai-import', 'info');
1499
1500 return [
1501 'status' => 'success',
1502 'data' => [
1503 'session_id' => $session_id,
1504 'process_id' => $process_id,
1505 'ai_page_ids' => $ai_page_ids,
1506 'saved' => $saved_count,
1507 // Pages the backend explicitly skipped — imported with the
1508 // pack's default content instead.
1509 'skipped' => $skipped_expected,
1510 // Readiness snapshot at import start. `missing` pages are NOT a
1511 // failure: the Finalizer pulls each on demand and waits for it.
1512 'expected' => $expected_ids,
1513 'ready' => $ready,
1514 'missing' => $missing,
1515 'platform' => isset($customization['platform']) ? $customization['platform'] : null,
1516 'customization_data' => $customization,
1517 'logo' => $logo,
1518 'errors' => $errors,
1519 ],
1520 ];
1521 }
1522
1523 /**
1524 * Validate API key against database
1525 * Checks if the provided API key exists for any user on the current site
1526 * Handles both single-site and multisite WordPress installations
1527 *
1528 * @param string $api_key The API key to validate
1529 * @return bool True if valid, false otherwise
1530 */
1531 private function validate_api_key_in_db($api_key) {
1532 global $wpdb;
1533
1534 $api_key = sanitize_text_field($api_key);
1535
1536 if (empty($api_key)) {
1537 return false;
1538 }
1539
1540 $meta_key = '_templately_api_key';
1541
1542 // Handle multisite: key will have site prefix in multisite
1543 if (is_multisite()) {
1544 // get_user_option() uses the format: {$wpdb->base_prefix}{$blog_id}_{$meta_key}
1545 // For current blog, we need to check with the current blog prefix
1546 $blog_id = get_current_blog_id();
1547 $meta_key = $wpdb->get_blog_prefix($blog_id) . $meta_key;
1548 }
1549
1550 // Query to check if this API key exists for any user
1551 $query = $wpdb->prepare(
1552 "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value = %s LIMIT 1",
1553 $meta_key,
1554 $api_key
1555 );
1556
1557 $user_id = $wpdb->get_var($query);
1558
1559 return !empty($user_id);
1560 }
1561 }
1562