PluginProbe
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! / 3.3.3
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! v3.3.3
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
← All changes | includes/API/AIContent.php +104 -1395 3.7.33.3.3 View file →
@@ -9,36 +9,18 @@
9 9
10 10 namespace Templately\API;
11 11
12 12 use Error;
13 -use Exception;
14 13 use Templately\Utils\Helper;
15 -use Templately\Utils\Database;
16 14 use WP_REST_Request;
17 -use WP_Error;
18 15 use Templately\Core\Importer\Utils\Utils;
19 16 use Templately\Core\Importer\Utils\AIUtils;
20 -use Templately\Core\Importer\Utils\SignatureVerifier;
21 -use Templately\Core\Importer\Parsers\WXR_Parser;
22 17
23 18 class AIContent extends API {
24 19 private $endpoint = 'ai-content';
25 20 private $dev_mode = false;
26 21
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 22
40 -
41 23 /**
42 24 * AIContent constructor.
43 25 *
44 26 * @param string $file File path.
@@ -44,8 +26,9 @@
44 26 * @param string $file File path.
45 27 * @param array $settings Settings.
46 28 */
47 29 public function __construct() {
30 + $this->dev_mode = (defined('TEMPLATELY_DEV') && TEMPLATELY_DEV) || (defined('IMPORT_DEBUG') && IMPORT_DEBUG);
48 31
49 32 parent::__construct();
50 33
51 34 }
@@ -51,40 +34,16 @@
51 34 }
52 35
53 36 public function _permission_check(WP_REST_Request $request) {
54 37 $this->request = $request;
55 - $this->api_key = $this->utils('options')->get( 'api_key' );
56 38 $process_id = $this->get_param('process_id');
57 39
58 40 $_route = $request->get_route();
59 41 if ('/templately/v1/ai-content/ai-update' === $_route || '/templately/v1/ai-content/ai-update-preview' === $_route) {
60 - // Disabled: the headers carry X-Templately-Apikey, and Helper::log()
61 - // writes to debug.log, which is web-readable on plenty of hosts. That
62 - // key authorizes this very route.
63 - // Helper::log( [
64 - // 'headers' => $request->get_headers(),
65 - // 'body' => $request->get_params(),
66 - // ], 'ai_update_request' );
67 -
68 42 if (empty($process_id)) {
69 43 return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'calculate_credit', 400);
70 44 }
71 45
72 - $header_api_key = sanitize_text_field($request->get_header('x_templately_apikey'));
73 - if (empty($header_api_key)) {
74 - $header_api_key = sanitize_text_field($request->get_header('X-Templately-Apikey'));
75 - }
76 -
77 - // Validate API key from header against database
78 - if (empty($header_api_key)) {
79 - return $this->error('missing_api_key', __('Missing API key in header.', 'templately'), 'ai-content/permission', 403);
80 - }
81 -
82 - $is_valid_key = $this->validate_api_key_in_db($header_api_key);
83 - if (!$is_valid_key) {
84 - return $this->error('invalid_api_key', __('Invalid API key provided in header.', 'templately'), 'ai-content/permission', 403);
85 - }
86 -
87 46 // Check AI process data using API key-based storage
88 47 $ai_process_data = AIUtils::get_ai_process_data();
89 48 if (is_array($ai_process_data) && !empty($ai_process_data[$process_id])) {
90 49 return true;
@@ -89,16 +48,12 @@
89 48 if (is_array($ai_process_data) && !empty($ai_process_data[$process_id])) {
90 49 return true;
91 50 }
92 51
93 - return (bool) AIUtils::get_matched_session_data($process_id);
52 + return (bool) Helper::get_matched_session_data($process_id);
94 53 }
95 54
96 - // // Allow access to attachments endpoint
97 - // if ('/templately/v1/ai-content/attachments' === $_route) {
98 - // return true;
99 - // }
100 - return parent::_permission_check($request);
55 + return parent::permission_check($request);
101 56 }
102 57
103 58
104 59 public function register_routes() {
@@ -105,125 +60,8 @@
105 60 // $this->get( $this->endpoint . '/calculate-credit', [ $this, 'calculate_credit' ] );
106 61 $this->post($this->endpoint . '/modify-content', [$this, 'modify_content']);
107 62 $this->post($this->endpoint . '/ai-update', [$this, 'ai_update']);
108 63 $this->post($this->endpoint . '/ai-update-preview', [$this, 'ai_update_preview']);
109 - $this->post($this->endpoint . '/generate-tagline', [$this, 'generate_tagline']);
110 - $this->get($this->endpoint . '/chatbot-conversation', [$this, 'get_chatbot_conversation'], [
111 - 'chat' => [
112 - 'required' => true,
113 - 'sanitize_callback' => 'sanitize_text_field',
114 - 'validate_callback' => function($param, $request, $key) {
115 - return is_string($param) && strlen($param) > 0 && strlen($param) <= 128 && preg_match('/^[A-Za-z0-9\-_]+$/', $param);
116 - },
117 - ],
118 - ]);
119 - $this->get($this->endpoint . '/chatbot-conversations', [$this, 'get_chatbot_conversations'], [
120 - 'page' => [
121 - 'required' => false,
122 - 'default' => 1,
123 - // absint, not the sanitize_text_field default — that would turn the
124 - // int into a string and corrupt anything non-string.
125 - 'sanitize_callback' => 'absint',
126 - ],
127 - 'per_page' => [
128 - 'required' => false,
129 - 'default' => 10,
130 - 'sanitize_callback' => 'absint',
131 - ],
132 - ]);
133 - $this->get($this->endpoint . '/chatbot-generated', [$this, 'get_chatbot_generated'], [
134 - 'chat' => [
135 - 'required' => true,
136 - 'sanitize_callback' => 'sanitize_text_field',
137 - 'validate_callback' => function($param, $request, $key) {
138 - return is_string($param) && strlen($param) > 0 && strlen($param) <= 128 && preg_match('/^[A-Za-z0-9\-_]+$/', $param);
139 - },
140 - ],
141 - ]);
142 - $this->post($this->endpoint . '/chatbot-detected-info', [$this, 'update_chatbot_detected_info'], [
143 - 'chat' => [
144 - 'required' => true,
145 - 'sanitize_callback' => 'sanitize_text_field',
146 - 'validate_callback' => function($param, $request, $key) {
147 - return is_string($param) && strlen($param) > 0 && strlen($param) <= 128 && preg_match('/^[A-Za-z0-9\-_]+$/', $param);
148 - },
149 - ],
150 - ]);
151 - $this->post($this->endpoint . '/chatbot-import-prepare', [$this, 'chatbot_import_prepare']);
152 - $this->post($this->endpoint . '/chatbot-mark-imported', [$this, 'mark_chatbot_imported'], [
153 - 'chat' => [
154 - 'required' => true,
155 - 'sanitize_callback' => 'sanitize_text_field',
156 - 'validate_callback' => function($param, $request, $key) {
157 - return is_string($param) && strlen($param) > 0 && strlen($param) <= 128 && preg_match('/^[A-Za-z0-9\-_]+$/', $param);
158 - },
159 - ],
160 - ]);
161 - $this->get($this->endpoint . '/attachments', [$this, 'get_attachments'], [
162 - 'type' => [
163 - 'default' => 'pack',
164 - 'required' => false,
165 - 'sanitize_callback' => 'sanitize_text_field',
166 - ],
167 - 'id' => [
168 - 'required' => false,
169 - 'sanitize_callback' => 'sanitize_text_field',
170 - ],
171 - 'pack_id' => [
172 - 'required' => false,
173 - 'sanitize_callback' => 'sanitize_text_field',
174 - ],
175 - ]);
176 - $this->get($this->endpoint . '/images', [$this, 'search_images'], [
177 - 'query' => [
178 - 'required' => false,
179 - 'sanitize_callback' => 'sanitize_text_field',
180 - 'validate_callback' => function($param, $request, $key) {
181 - return is_string($param) && strlen($param) <= 255;
182 - },
183 - ],
184 - 'orientation' => [
185 - 'required' => false,
186 - 'default' => 'all',
187 - 'sanitize_callback' => 'sanitize_text_field',
188 - 'validate_callback' => function($param, $request, $key) {
189 - $allowed_orientations = ['all', 'landscape', 'portrait', 'square'];
190 - return in_array($param, $allowed_orientations, true);
191 - },
192 - ],
193 - 'size' => [
194 - 'required' => false,
195 - 'default' => 'medium',
196 - 'sanitize_callback' => 'sanitize_text_field',
197 - 'validate_callback' => function($param, $request, $key) {
198 - $allowed_sizes = ['small', 'medium', 'large'];
199 - return in_array($param, $allowed_sizes, true);
200 - },
201 - ],
202 - 'color' => [
203 - 'required' => false,
204 - 'sanitize_callback' => 'sanitize_text_field',
205 - 'validate_callback' => function($param, $request, $key) {
206 - return is_string($param) && strlen($param) <= 50;
207 - },
208 - ],
209 - 'page' => [
210 - 'required' => false,
211 - 'default' => 1,
212 - 'sanitize_callback' => 'absint',
213 - 'validate_callback' => function($param, $request, $key) {
214 - return is_numeric($param) && $param > 0 && $param <= 1000;
215 - },
216 - ],
217 - 'per_page' => [
218 - 'required' => false,
219 - 'default' => 20,
220 - 'sanitize_callback' => 'absint',
221 - 'validate_callback' => function($param, $request, $key) {
222 - return is_numeric($param) && $param > 0 && $param <= 100;
223 - },
224 - ],
225 - ]);
226 64 // die(rest_url( 'templately/v1/ai-content/ai-update' ));
227 65 }
228 66
229 67 public function calculate_credit() {
@@ -239,17 +77,24 @@
239 77 if (empty($pack_id)) {
240 78 return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'calculate_credit', 400);
241 79 }
242 80
243 - $extra_headers = [
244 - 'Accept' => 'application/json',
245 - ];
246 - $response = Helper::make_api_get_request("v2/ai/calculate-credit/pack/$pack_id", [], $extra_headers, 30);
81 + $response = wp_remote_get($this->get_api_url("ai/calculate-credit/pack/$pack_id"), [
82 + 'timeout' => 30,
83 + 'headers' => [
84 + 'Accept' => 'application/json',
85 + 'Content-Type' => 'application/json',
86 + 'Authorization' => 'Bearer ' . $this->api_key,
87 + 'x-templately-ip' => Helper::get_ip(),
88 + 'x-templately-url' => home_url('/'),
89 + 'x-templately-version' => TEMPLATELY_VERSION,
90 + ]
91 + ]);
247 92
248 93
249 94 // return $response;
250 95 if (is_wp_error($response)) {
251 - return $this->error('request_failed', __('Request failed.', 'templately'), 'calculate_credit', 500, ['error_detail' => $response->get_error_message()]);
96 + return $this->error('request_failed', __('Request failed.', 'templately'), 'calculate_credit', 500, $response);
252 97 }
253 98
254 99 $body = wp_remote_retrieve_body($response);
255 100 $data = json_decode($body, true);
@@ -271,31 +116,19 @@
271 116 $isBusinessNichesNew = $this->get_param('isBusinessNichesNew', false);
272 117 $ai_page_ids = $this->get_param('ai_page_ids', [], null);
273 118 $content_ids = $this->get_param('content_ids', [], null);
274 119 $session_id = $this->get_param('session_id'); // Add session_id parameter
275 -
276 - // Security: Sanitize session_id if provided
277 - if (!empty($session_id)) {
278 - $session_id = AIUtils::sanitize_path_component($session_id, 'session_id');
279 - if (is_wp_error($session_id)) {
280 - return $session_id;
281 - }
282 - }
283 -
284 120 $preview_pages = $this->get_param('preview_pages', [], null);
285 - $image_replace = $this->get_param('imageReplace', [], null);
286 121 $platform = $this->get_param('platform');
287 - $language = $this->get_param('language', null);
288 122
289 123 // ai content fields
290 - $name = $this->get_param('name');
291 - $category = $this->get_param('category');
292 - $description = $this->get_param('description');
293 - $email = $this->get_param('email');
294 - $contactNumber = $this->get_param('contactNumber');
295 - $businessAddress = $this->get_param('businessAddress');
296 - $openingHour = $this->get_param('openingHour');
297 - $requested_platform = $this->get_param('requested_platform', 'templately');
124 + $name = $this->get_param('name');
125 + $category = $this->get_param('category');
126 + $description = $this->get_param('description');
127 + $email = $this->get_param('email');
128 + $contactNumber = $this->get_param('contactNumber');
129 + $businessAddress = $this->get_param('businessAddress');
130 + $openingHour = $this->get_param('openingHour');
298 131
299 132 if (empty($pack_id)) {
300 133 return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'modify_content', 400);
301 134 }
@@ -312,39 +145,35 @@
312 145
313 146 // $response = get_transient( '__templately_ai_process_id' );
314 147
315 148 // if(empty($response)) {
316 - $extra_headers = [
317 - 'Accept' => 'application/json',
318 - 'x-templately-session-id' => $session_id,
319 - 'x-templately-requested-platform' => $requested_platform,
320 - ];
321 - $body_data = [
322 - 'business_name' => $name,
323 - 'business_niches' => $category,
324 - 'prompt' => $description,
325 - 'email' => $email,
326 - 'phone' => $contactNumber,
327 - 'address' => $businessAddress,
328 - 'openingHour' => $openingHour,
329 - 'pack_id' => $pack_id,
330 - 'content_ids' => $content_ids,
331 - 'platform' => $platform,
332 - 'preview_pages' => $preview_pages,
333 - 'language' => $language,
334 - 'callback' => defined('TEMPLATELY_CALLBACK') ? TEMPLATELY_CALLBACK . '/wp-json/templately/v1/ai-content/ai-update' : rest_url('templately/v1/ai-content/ai-update'),
335 - ];
336 - /**
337 - * Filter body data before making API request to modify-content endpoint
338 - *
339 - * @since 3.5.0
340 - * @param array $body_data The request body data
341 - * @param WP_REST_Request $request The REST request object
342 - */
343 - $body_data = apply_filters( 'templately_ai_modify_content_body_data', $body_data, $this->request );
149 + $response = wp_remote_post($this->get_api_url("ai/modify-content/pack"), [
150 + 'timeout' => 15 * MINUTE_IN_SECONDS,
151 + 'headers' => [
152 + 'Accept' => 'application/json',
153 + 'Content-Type' => 'application/json',
154 + 'Authorization' => 'Bearer ' . $this->api_key,
155 + 'x-templately-ip' => Helper::get_ip(),
156 + 'x-templately-url' => home_url('/'),
157 + 'x-templately-version' => TEMPLATELY_VERSION,
158 + 'x-templately-session-id' => $session_id,
159 + ],
160 + 'body' => json_encode([
161 + 'business_name' => $name,
162 + 'business_niches' => $category,
163 + 'prompt' => $description,
164 + 'email' => $email,
165 + 'phone' => $contactNumber,
166 + 'address' => $businessAddress,
167 + 'openingHour' => $openingHour,
168 + 'pack_id' => $pack_id,
169 + 'content_ids' => $content_ids,
170 + 'platform' => $platform,
171 + 'preview_pages' => $preview_pages,
172 + 'callback' => defined('TEMPLATELY_CALLBACK') ? TEMPLATELY_CALLBACK . '/wp-json/templately/v1/ai-content/ai-update' : rest_url('templately/v1/ai-content/ai-update'),
173 + ]),
174 + ]);
344 175
345 - $response = Helper::make_api_post_request('v2/ai/modify-content/pack', $body_data, $extra_headers, 15 * MINUTE_IN_SECONDS);
346 -
347 176 // set_transient( '__templately_ai_process_id', $response, 60 * 60 * 24 * 30 );
348 177 // }
349 178
350 179 $bk_ai_business_niches = get_option('templately_ai_business_niches', []);
@@ -355,9 +184,9 @@
355 184
356 185 // return $response;
357 186 if (is_wp_error($response)) {
358 187 error_log(print_r($response, true));
359 - return $this->error('request_failed', __('Request failed.', 'templately'), 'modify_content', 500, ['error_data' => $response->get_error_data()]);
188 + return $this->error('request_failed', __('Request failed.', 'templately'), 'modify_content', 500, $response->additional_data);
360 189 }
361 190
362 191 $body = wp_remote_retrieve_body($response);
363 192 $data = json_decode($body, true);
@@ -362,9 +191,9 @@
362 191 $body = wp_remote_retrieve_body($response);
363 192 $data = json_decode($body, true);
364 193 // error status is ok, if status is error then return as is
365 194 if (! is_array($data) || ! isset($data['status'])) {
366 - return $this->error('invalid_response', __('Invalid response.', 'templately'), 'modify_content', 500, ['data' => $data]);
195 + return $this->error('invalid_response', __('Invalid response.', 'templately'), 'modify_content', 500, $data);
367 196 }
368 197
369 198 // "{"status":"success","message":"The content is being generated in the queue","process_id":"01JRQQD39GNWTNF18EWF8YH0BG-271838-pack-408"}"
370 199 if (isset($data['status']) && $data['status'] === 'success' && isset($data['process_id'])) {
@@ -369,51 +198,45 @@
369 198 // "{"status":"success","message":"The content is being generated in the queue","process_id":"01JRQQD39GNWTNF18EWF8YH0BG-271838-pack-408"}"
370 199 if (isset($data['status']) && $data['status'] === 'success' && isset($data['process_id'])) {
371 200 $process_id = $data['process_id'];
372 201
373 - // // Save templates to files if available using the common function
374 - // if (!empty($data['templates']) && is_array($data['templates'])) {
375 - // foreach ($data['templates'] as $content_id => $template_data) {
376 - // // Decode template if it's base64 encoded
377 - // if (! empty($template_data) && base64_decode($template_data, true) !== false) {
378 - // $data['templates'][$content_id] = base64_decode($template_data);
379 - // }
202 + // Save templates to files if available using the common function
203 + if (!empty($data['templates']) && is_array($data['templates'])) {
204 + foreach ($data['templates'] as $content_id => $template_data) {
205 + // Decode template if it's base64 encoded
206 + if (! empty($template_data) && base64_decode($template_data, true) !== false) {
207 + $data['templates'][$content_id] = base64_decode($template_data);
208 + }
380 209
381 - // if (!empty($template_data)) {
382 - // AIUtils::save_template_to_file(
383 - // $process_id,
384 - // $content_id,
385 - // $template_data,
386 - // $ai_page_ids,
387 - // true, // Always use preview mode for AI content workflow
388 - // isset($template_data['isSkipped']) ? $template_data['isSkipped'] : false
389 - // );
390 - // }
391 - // }
392 - // }
210 + if (!empty($template_data)) {
211 + Helper::save_template_to_file(
212 + $process_id,
213 + $content_id,
214 + $template_data,
215 + $ai_page_ids,
216 + true, // Always use preview mode for AI content workflow
217 + isset($template_data['isSkipped']) ? $template_data['isSkipped'] : false
218 + );
219 + }
220 + }
221 + }
393 222
394 - $user = $this->utils('options')->get('user');
395 -
396 223 $ai_process_data[$process_id] = [
397 - 'name' => $name,
398 - 'category' => $category,
399 - 'description' => $description,
400 - 'email' => $email,
401 - 'contactNumber' => $contactNumber,
402 - 'businessAddress' => $businessAddress,
403 - 'openingHour' => $openingHour,
404 - 'process_id' => $process_id,
405 - 'pack_id' => $pack_id,
406 - 'ai_page_ids' => $ai_page_ids,
407 - 'ai_preview_ids' => $preview_pages,
408 - 'content_ids' => $content_ids,
409 - 'platform' => $platform,
410 - 'api_key' => $this->api_key,
411 - 'user_id' => isset($user['id']) ? $user['id'] : null,
412 - 'session_id' => $session_id,
413 - 'imageReplace' => $image_replace,
414 - 'language' => $language,
415 - 'requested_platform' => $requested_platform,
224 + 'name' => $name,
225 + 'category' => $category,
226 + 'description' => $description,
227 + 'email' => $email,
228 + 'contactNumber' => $contactNumber,
229 + 'businessAddress' => $businessAddress,
230 + 'openingHour' => $openingHour,
231 + 'process_id' => $process_id,
232 + 'pack_id' => $pack_id,
233 + 'ai_page_ids' => $ai_page_ids,
234 + 'ai_preview_ids' => $preview_pages,
235 + 'content_ids' => $content_ids,
236 + 'platform' => $platform,
237 + 'api_key' => $this->api_key,
238 + 'session_id' => $session_id, // Store session_id for coordination
416 239 ];
417 240
418 241 // Update using API key-based storage with automatic count-based cleanup
419 242 AIUtils::update_ai_process_data($ai_process_data);
@@ -459,24 +282,24 @@
459 282 ];
460 283 }
461 284
462 285 // Always use preview mode for AI content workflow
463 - // Validate and get process data using centralized method
464 - $process_data = AIUtils::validate_and_get_process_data($process_id);
465 - if (is_wp_error($process_data)) {
466 - return $process_data;
286 + // Get AI process data using API key-based storage
287 + $ai_process_data = AIUtils::get_ai_process_data();
288 +
289 + if (empty($ai_process_data[$process_id]['ai_page_ids'])) {
290 + return $this->error('invalid_process_id', __('Invalid process id.', 'templately'), 'ai-content/ai-update', 400);
467 291 }
468 292
469 - $session_id = $process_data['session_id'];
470 - $ai_page_ids = $process_data['ai_page_ids'];
293 + $ai_page_ids = $ai_process_data[$process_id]['ai_page_ids'];
471 294
472 - // Use the common helper function to save the template
473 - $result = AIUtils::save_template_to_file(
295 + // Use the common helper function to save the template (always preview mode)
296 + $result = Helper::save_template_to_file(
474 297 $process_id,
475 - $session_id,
476 298 $content_id,
477 299 $template,
478 300 $ai_page_ids,
301 + true, // Always use preview mode
479 302 $isSkipped
480 303 );
481 304
482 305 if(is_wp_error($result)){
@@ -520,16 +343,16 @@
520 343 return $this->error('invalid_template', __('Template must be a non-empty array with content_id as keys.', 'templately'), 'ai-content/ai-update-preview', 400);
521 344 }
522 345
523 346 // Always use preview mode for AI content workflow
524 - // Validate and get process data using centralized method
525 - $process_data = AIUtils::validate_and_get_process_data($process_id);
526 - if (is_wp_error($process_data)) {
527 - return $process_data;
347 + // Get AI process data using API key-based storage
348 + $ai_process_data = AIUtils::get_ai_process_data();
349 +
350 + if (empty($ai_process_data[$process_id]['ai_page_ids'])) {
351 + return $this->error('invalid_process_id', __('Invalid process id.', 'templately'), 'ai-content/ai-update-preview', 400);
528 352 }
529 353
530 - $session_id = $process_data['session_id'];
531 - $ai_page_ids = $process_data['ai_page_ids'];
354 + $ai_page_ids = $ai_process_data[$process_id]['ai_page_ids'];
532 355 $results = [];
533 356 $success_count = 0;
534 357 $error_count = 0;
535 358
@@ -535,14 +358,14 @@
535 358
536 359 // Process each content_id/template pair
537 360 foreach ($template as $content_id => $template_data) {
538 361 // Use the common helper function to save the template (always preview mode)
539 - $result = AIUtils::save_template_to_file(
362 + $result = Helper::save_template_to_file(
540 363 $process_id,
541 - $session_id,
542 364 $content_id,
543 365 $template_data,
544 366 $ai_page_ids,
367 + true, // Always use preview mode
545 368 $isSkipped
546 369 );
547 370
548 371 $results[$content_id] = $result;
@@ -572,1123 +395,9 @@
572 395 }
573 396
574 397
575 398
576 - /**
577 - * Get attachments from API endpoint
578 - *
579 - * @return array|\WP_Error
580 - */
581 - public function get_attachments() {
582 - // Get parameters from request
583 - $type = $this->get_param('type', 'pack');
584 - $id = $this->get_param('pack_id');
585 - $requested_platform = $this->get_param('requested_platform', 'templately');
586 -
587 - // Require ID parameter - return error if not provided
588 - if (empty($id)) {
589 - return $this->error('missing_id', __('Pack ID or ID parameter is required.', 'templately'), 'get_attachments', 400);
590 - }
591 -
592 - try {
593 - // Construct API endpoint URL
594 - $api_endpoint = "get-xml-attachment/{$type}/{$id}";
595 -
596 - // Make API call
597 - $extra_headers = [
598 - 'Accept' => 'application/xml, text/xml',
599 - 'x-templately-requested-platform' => $requested_platform,
600 - ];
601 - $response = Helper::make_api_get_request("v2/$api_endpoint", [], $extra_headers, 30);
602 -
603 - // Check for HTTP errors
604 - if (is_wp_error($response)) {
605 - return $this->error('api_request_failed', __('Failed to fetch attachments from API.', 'templately'), 'get_attachments', 500, ['error_detail' => $response->get_error_message()]);
606 - }
607 -
608 - $response_code = wp_remote_retrieve_response_code($response);
609 - $xml_content = wp_remote_retrieve_body($response);
610 -
611 - if ($response_code !== 200) {
612 - // check if $xml_content contains valid json
613 - // ex. '{"status":"error","message":"Attachment XML file not found in pack archive."}'
614 - $error_data = @json_decode($xml_content, true);
615 - if(is_array($error_data) && isset($error_data['status']) && $error_data['status'] === 'error' && !empty($error_data['message'])){
616 - return $this->error('api_http_error', $error_data['message'], 'get_attachments', $response_code);
617 - }
618 - return $this->error('api_http_error', sprintf(__('API returned HTTP %d error.', 'templately'), $response_code), 'get_attachments', $response_code);
619 - }
620 -
621 - // Validate we have XML content
622 - if (empty($xml_content)) {
623 - return $this->error('no_xml_content', __('No XML content found in API response.', 'templately'), 'get_attachments', 404);
624 - }
625 -
626 - // Parse the XML content from API response
627 - $parsed_data = $this->parse_xml_content($xml_content);
628 -
629 - if (is_wp_error($parsed_data)) {
630 - return $this->error('xml_parse_error', __('Failed to parse XML content.', 'templately'), 'get_attachments', 500, ['error_detail' => $parsed_data->get_error_message()]);
631 - }
632 -
633 - // Extract attachments from parsed data
634 - $attachments = $this->extract_attachments_from_parsed_data($parsed_data);
635 -
636 - return [
637 - 'status' => 'success',
638 - 'data' => $attachments,
639 - 'message' => sprintf(__('Found %d attachments.', 'templately'), count($attachments)),
640 - ];
641 -
642 - } catch (Exception $e) {
643 - return $this->error('exception', __('An unexpected error occurred while fetching attachments.', 'templately'), 'get_attachments', 500, ['error_detail' => $e->getMessage()]);
644 - }
645 - }
646 -
647 -
648 -
649 - /**
650 - * Parse XML content string using WXR Parser
651 - *
652 - * @param string $xml_content XML content string
653 - * @return array|\WP_Error Parsed data or error
654 - */
655 - private function parse_xml_content($xml_content) {
656 - // Ensure WordPress filesystem functions are available
657 - if (!function_exists('wp_tempnam')) {
658 - require_once(ABSPATH . 'wp-admin/includes/file.php');
659 - }
660 -
661 - // Create a temporary file to store XML content
662 - $temp_file = wp_tempnam('templately_attachments');
663 - if (!$temp_file) {
664 - return new WP_Error('temp_file_failed', __('Failed to create temporary file.', 'templately'));
665 - }
666 -
667 - // Write XML content to temporary file
668 - $bytes_written = file_put_contents($temp_file, $xml_content);
669 - if ($bytes_written === false) {
670 - unlink($temp_file);
671 - return new WP_Error('write_failed', __('Failed to write XML content to temporary file.', 'templately'));
672 - }
673 -
674 - try {
675 - // Initialize WXR Parser
676 - $parser = new WXR_Parser();
677 -
678 - // Parse the temporary XML file
679 - $parsed_data = $parser->parse($temp_file);
680 -
681 - // Clean up temporary file
682 - unlink($temp_file);
683 -
684 - return $parsed_data;
685 -
686 - } catch (Exception $e) {
687 - // Clean up temporary file on exception
688 - if (file_exists($temp_file)) {
689 - unlink($temp_file);
690 - }
691 - return new WP_Error('parse_exception', $e->getMessage());
692 - }
693 - }
694 -
695 - /**
696 - * Extract attachments from parsed WXR data
697 - *
698 - * @param array $parsed_data Parsed WXR data
699 - * @return array Array of attachment data
700 - */
701 - private function extract_attachments_from_parsed_data($parsed_data) {
702 - $attachments = [];
703 -
704 - if (isset($parsed_data['posts']) && is_array($parsed_data['posts'])) {
705 - foreach ($parsed_data['posts'] as $post) {
706 - // Check if this is an attachment
707 - if (isset($post['post_type']) && $post['post_type'] === 'attachment') {
708 - $attachment = [
709 - 'id' => isset($post['post_id']) ? (int) $post['post_id'] : 0,
710 - 'url' => isset($post['attachment_url']) ? (string) $post['attachment_url'] : '',
711 - 'title' => isset($post['post_title']) ? (string) $post['post_title'] : '',
712 - 'type' => isset($post['attachment_type']) ? (string) $post['attachment_type'] : '',
713 - ];
714 -
715 - // Extract metadata including dimensions and medium URL
716 - $metadata = $this->extract_medium_size_url($post, $attachment['url']);
717 -
718 - // Filter out small images (width or height <= 150px) to ignore small icons
719 - if ($metadata && isset($metadata['width']) && isset($metadata['height'])) {
720 - if ($metadata['width'] < 150 || $metadata['height'] < 150) {
721 - continue; // Skip small images/icons
722 - }
723 -
724 - // Add dimensions to attachment data
725 - $attachment['width'] = $metadata['width'];
726 - $attachment['height'] = $metadata['height'];
727 -
728 - // Add medium URL if available
729 - if (isset($metadata['medium_url'])) {
730 - $attachment['medium_url'] = $metadata['medium_url'];
731 - }
732 - } else {
733 - // Skip attachments without metadata or dimensions
734 - continue;
735 - }
736 -
737 - // Only add if we have the required data
738 - if ($attachment['id'] && $attachment['url'] && $attachment['title']) {
739 - $attachments[] = $attachment;
740 - }
741 - }
742 - }
743 - }
744 -
745 - return $attachments;
746 - }
747 -
748 - /**
749 - * Extract medium size URL from attachment metadata and get image dimensions
750 - *
751 - * @param array $post Post data from WXR parser
752 - * @param string $original_url Original attachment URL
753 - * @return array|null Array with medium_url and dimensions if found, null otherwise
754 - */
755 - private function extract_medium_size_url($post, $original_url) {
756 - if (!isset($post['postmeta']) || !is_array($post['postmeta'])) {
757 - return null;
758 - }
759 -
760 - foreach ($post['postmeta'] as $meta) {
761 - if (!isset($meta['key']) || !isset($meta['value'])) {
762 - continue;
763 - }
764 -
765 - // Only check _wp_attachment_metadata
766 - if ($meta['key'] === '_wp_attachment_metadata') {
767 - $attachment_metadata = @unserialize($meta['value']);
768 - if (is_array($attachment_metadata)) {
769 - $result = [];
770 -
771 - // Get original image dimensions
772 - $width = isset($attachment_metadata['width']) ? (int) $attachment_metadata['width'] : 0;
773 - $height = isset($attachment_metadata['height']) ? (int) $attachment_metadata['height'] : 0;
774 -
775 - $result['width'] = $width;
776 - $result['height'] = $height;
777 -
778 - // Check if medium size exists
779 - if (isset($attachment_metadata['sizes']['medium']['file'])) {
780 - // Construct medium URL from original URL and medium filename
781 - $medium_filename = $attachment_metadata['sizes']['medium']['file'];
782 - $original_path = dirname(parse_url($original_url, PHP_URL_PATH));
783 - $base_url = str_replace(parse_url($original_url, PHP_URL_PATH), '', $original_url);
784 - $result['medium_url'] = $base_url . $original_path . '/' . $medium_filename;
785 - }
786 -
787 - return $result;
788 - }
789 - }
790 - }
791 -
792 - return null;
793 - }
794 -
795 -
796 -
797 - /**
798 - * Search images endpoint
799 - *
800 - * @param WP_REST_Request $request
801 - * @return WP_REST_Response|WP_Error
802 - */
803 - public function search_images(WP_REST_Request $request) {
804 - // Get and sanitize parameters
805 - $query = $this->get_param('query', '');
806 - $orientation = $this->get_param('orientation', 'all');
807 - $size = $this->get_param('size', 'medium');
808 - $color = $this->get_param('color', '');
809 - $page = $this->get_param('page', 1, 'absint');
810 - $per_page = $this->get_param('per_page', 20, 'absint');
811 -
812 - // Validate required query parameter
813 - if (empty($query)) {
814 - return $this->error(
815 - 'missing_query',
816 - __('Search query is required.', 'templately'),
817 - 'search_images',
818 - 400
819 - );
820 - }
821 -
822 - // Prepare API request parameters
823 - $api_params = [
824 - 'query' => urlencode($query),
825 - 'page' => $page,
826 - 'per_page' => $per_page,
827 - ];
828 -
829 - // Add optional parameters if provided
830 - if ($orientation !== 'all') {
831 - $api_params['orientation'] = $orientation;
832 - }
833 -
834 - if (!empty($size)) {
835 - $api_params['size'] = $size;
836 - }
837 -
838 - if (!empty($color)) {
839 - $api_params['color'] = $color;
840 - }
841 -
842 - // Make API request to external image service
843 - $extra_headers = [
844 - 'Content-Type' => 'application/json',
845 - ];
846 -
847 - $response = Helper::make_api_get_request('v2/images', $api_params, $extra_headers, 30);
848 -
849 - // Handle API response errors
850 - if (is_wp_error($response)) {
851 - return $this->error(
852 - 'api_request_failed',
853 - __('Failed to fetch images from external service.', 'templately'),
854 - 'search_images',
855 - 500
856 - );
857 - }
858 -
859 - $response_code = wp_remote_retrieve_response_code($response);
860 - $response_body = wp_remote_retrieve_body($response);
861 -
862 - if ($response_code !== 200) {
863 - return $this->error(
864 - 'api_response_error',
865 - sprintf(__('External API returned error code: %d', 'templately'), $response_code),
866 - 'search_images',
867 - $response_code
868 - );
869 - }
870 -
871 - // Parse and validate response
872 - $data = json_decode($response_body, true);
873 - if (json_last_error() !== JSON_ERROR_NONE) {
874 - return $this->error(
875 - 'invalid_response',
876 - __('Invalid response from external service.', 'templately'),
877 - 'search_images',
878 - 500
879 - );
880 - }
881 -
882 - // Check if the response has the expected structure and success status
883 - if (!isset($data['status']) || $data['status'] !== 'success') {
884 - return $this->error(
885 - 'api_response_error',
886 - __('External API returned an error status.', 'templately'),
887 - 'search_images',
888 - 500
889 - );
890 - }
891 -
892 - // Extract nested data from the response
893 - $response_data = $data['data'] ?? [];
894 - $images = $response_data['images'] ?? [];
895 - $total_results = $response_data['total_results'] ?? 0;
896 - $current_page = $response_data['page'] ?? $page;
897 - $per_page_count = $response_data['per_page'] ?? $per_page;
898 -
899 - // Return successful response with properly mapped data
900 - return $this->success([
901 - 'images' => $images,
902 - 'total' => $total_results,
903 - 'page' => $current_page,
904 - 'per_page' => $per_page_count,
905 - 'total_pages' => $total_results > 0 ? ceil($total_results / $per_page_count) : 0,
906 - ]);
907 - }
908 -
909 -
910 -
911 - /**
912 - * Generate tagline using AI
913 - *
914 - * @return array|WP_Error
915 - */
916 - public function generate_tagline() {
917 - // Get parameters
918 - $prompt = $this->get_param('prompt');
919 - $requested_platform = $this->get_param('requested_platform', 'templately');
920 -
921 - // Validate required parameters
922 - if (empty($prompt)) {
923 - return $this->error(
924 - 'missing_prompt',
925 - __('Prompt is required for tagline generation.', 'templately'),
926 - 'generate_tagline',
927 - 400
928 - );
929 - }
930 -
931 - // Prepare request body
932 - $body_data = [
933 - 'prompt' => $prompt,
934 - ];
935 -
936 - // Make API request
937 - $extra_headers = [
938 - 'Content-Type' => 'application/json',
939 - 'x-templately-requested-platform' => $requested_platform,
940 - ];
941 -
942 - $response = Helper::make_api_post_request('v2/generate-tagline', $body_data, $extra_headers, 30);
943 -
944 - // Handle API response errors
945 - if (is_wp_error($response)) {
946 - return $this->error(
947 - 'api_request_failed',
948 - __('Failed to generate tagline.', 'templately'),
949 - 'generate_tagline',
950 - 500,
951 - ['error_detail' => $response->get_error_message()]
952 - );
953 - }
954 -
955 - $response_code = wp_remote_retrieve_response_code($response);
956 - $response_body = wp_remote_retrieve_body($response);
957 -
958 - if ($response_code !== 200) {
959 - // Try to parse the response body as JSON to get specific error details
960 - $data = json_decode($response_body, true);
961 -
962 - // If valid JSON, extract error message and return with proper status code
963 - if (json_last_error() === JSON_ERROR_NONE && is_array($data)) {
964 - $error_message = isset($data['message']) ? $data['message'] : __('Something went wrong. Please try again or contact support.', 'templately');
965 - return $this->error(
966 - 'api_response_error',
967 - $error_message,
968 - 'generate_tagline',
969 - $response_code
970 - );
971 - }
972 -
973 - // Otherwise, return generic error
974 - return $this->error(
975 - 'api_response_error',
976 - __('Something went wrong. Please try again or contact support.', 'templately'),
977 - 'generate_tagline',
978 - $response_code
979 - );
980 - }
981 -
982 - // Parse and validate response
983 - $data = json_decode($response_body, true);
984 - if (json_last_error() !== JSON_ERROR_NONE) {
985 - return $this->error(
986 - 'invalid_response',
987 - __('Invalid response from API.', 'templately'),
988 - 'generate_tagline',
989 - 500
990 - );
991 - }
992 -
993 - // Check if the response has the expected structure
994 - if (!isset($data['status'])) {
995 - return $this->error(
996 - 'api_response_error',
997 - __('API returned an unexpected response.', 'templately'),
998 - 'generate_tagline',
999 - 500
1000 - );
1001 - }
1002 -
1003 - // Return the response as-is
1004 - return $data;
1005 - }
1006 -
1007 - /**
1008 - * Fetch a chatbot conversation by ID from the external Templately chatbot API.
1009 - *
1010 - * Used to resume a conversation that began on templately.dev when the user
1011 - * is redirected into the plugin with ?process=ai&chat={uuid}.
1012 - *
1013 - * @return array|\WP_Error Pass-through of the external response { status, data } or WP_Error.
1014 - */
1015 - public function get_chatbot_conversation() {
1016 - $chat = $this->get_param('chat');
1017 -
1018 - if (empty($chat)) {
1019 - return $this->error('invalid_chat_id', __('Invalid conversation ID.', 'templately'), 'ai-content/chatbot-conversation', 400);
1020 - }
1021 -
1022 - $extra_headers = [
1023 - 'Accept' => 'application/json',
1024 - ];
1025 - $response = Helper::make_api_get_request("v2/chatbot/conversation/{$chat}", [], $extra_headers, 30);
1026 -
1027 - if (is_wp_error($response)) {
1028 - return $this->error('request_failed', __('Failed to fetch conversation.', 'templately'), 'ai-content/chatbot-conversation', 500, ['error_detail' => $response->get_error_message()]);
1029 - }
1030 -
1031 - $response_code = wp_remote_retrieve_response_code($response);
1032 - $body = wp_remote_retrieve_body($response);
1033 - $data = json_decode($body, true);
1034 -
1035 - if ($response_code !== 200) {
1036 - $message = (is_array($data) && !empty($data['message'])) ? $data['message'] : sprintf(__('API returned HTTP %d error.', 'templately'), $response_code);
1037 - return $this->error('api_http_error', $message, 'ai-content/chatbot-conversation', $response_code);
1038 - }
1039 -
1040 - if (!is_array($data) || !isset($data['status'])) {
1041 - return $this->error('invalid_response', __('Invalid response.', 'templately'), 'ai-content/chatbot-conversation', 500);
1042 - }
1043 -
1044 - return $data;
1045 - }
1046 -
1047 - /**
1048 - * List the connected account's generated AI sites, newest first.
1049 - *
1050 - * Backs the "My AI Sites" screen, which exists so a user can re-import a
1051 - * generation at any time instead of having to keep its templately.com link.
1052 - *
1053 - * Each row carries `can_import` / `is_expired` / `is_pro` / `expires_at`,
1054 - * computed server-side (free accounts get 7 days from generation, entitled
1055 - * accounts import forever). Render those as given — recomputing the window
1056 - * here would silently drift from the backend the moment the rule changes.
1057 - *
1058 - * @return array|\WP_Error Pass-through of { status, current_page, total_page, total, data } or WP_Error.
1059 - */
1060 - public function get_chatbot_conversations() {
1061 - $page = max(1, (int) $this->get_param('page', 1, 'absint'));
1062 - $per_page = min(100, max(1, (int) $this->get_param('per_page', 10, 'absint')));
1063 -
1064 - $extra_headers = [
1065 - 'Accept' => 'application/json',
1066 - ];
1067 - $response = Helper::make_api_get_request('v2/chatbot/conversations', [
1068 - 'page' => $page,
1069 - 'per_page' => $per_page,
1070 - ], $extra_headers, 30);
1071 -
1072 - if (is_wp_error($response)) {
1073 - return $this->error('request_failed', __('Failed to fetch your AI sites.', 'templately'), 'ai-content/chatbot-conversations', 500, ['error_detail' => $response->get_error_message()]);
1074 - }
1075 -
1076 - $response_code = wp_remote_retrieve_response_code($response);
1077 - $body = wp_remote_retrieve_body($response);
1078 - $data = json_decode($body, true);
1079 -
1080 - if ($response_code !== 200) {
1081 - $message = (is_array($data) && !empty($data['message'])) ? $data['message'] : sprintf(__('API returned HTTP %d error.', 'templately'), $response_code);
1082 - return $this->error('api_http_error', $message, 'ai-content/chatbot-conversations', $response_code);
1083 - }
1084 -
1085 - if (!is_array($data) || !isset($data['status'])) {
1086 - return $this->error('invalid_response', __('Invalid response.', 'templately'), 'ai-content/chatbot-conversations', 500);
1087 - }
1088 -
1089 - return $data;
1090 - }
1091 -
1092 - /**
1093 - * Fetch the server-side generated content for a chatbot conversation (Phase 2).
1094 - *
1095 - * In Phase 2 the AI content is generated on the backend. This proxy mirrors
1096 - * {@see get_chatbot_conversation()} and returns the already-generated page
1097 - * content, customization data and signed logo URL so the plugin can run a
1098 - * thin import without triggering generation or the customizer locally.
1099 - *
1100 - * @return array|\WP_Error Pass-through of the external response { status, data } or WP_Error.
1101 - */
1102 - public function get_chatbot_generated() {
1103 - $chat = $this->get_param('chat');
1104 -
1105 - if (empty($chat)) {
1106 - return $this->error('invalid_chat_id', __('Invalid conversation ID.', 'templately'), 'ai-content/chatbot-generated', 400);
1107 - }
1108 -
1109 - $extra_headers = [
1110 - 'Accept' => 'application/json',
1111 - ];
1112 - $response = Helper::make_api_get_request("v2/chatbot/generated/{$chat}", [], $extra_headers, 30);
1113 -
1114 - if (is_wp_error($response)) {
1115 - return $this->error('request_failed', __('Failed to fetch generated content.', 'templately'), 'ai-content/chatbot-generated', 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-generated', $response_code);
1125 - }
1126 -
1127 - if (!is_array($data) || !isset($data['status'])) {
1128 - return $this->error('invalid_response', __('Invalid response.', 'templately'), 'ai-content/chatbot-generated', 500);
1129 - }
1130 -
1131 - // The direct-import handoff reads this endpoint and then immediately calls
1132 - // chatbot-import-prepare, which pulls the very same (large) bundle off GCP
1133 - // seconds later. Park it so prepare can reuse it instead of paying for a
1134 - // second identical transfer.
1135 - Database::set_transient(self::GENERATED_CACHE_KEY . $chat, $data, self::GENERATED_CACHE_TTL);
1136 -
1137 - return $data;
1138 - }
1139 -
1140 - /**
1141 - * Persist edited detected-info back to the chatbot conversation (Phase 2).
1142 - *
1143 - * Mirrors {@see get_chatbot_conversation()} / {@see get_chatbot_generated()}
1144 - * but forwards a POST. When the user edits the detected-info card in the
1145 - * sidebar, the plugin proxies the corrected values to the backend so a later
1146 - * replay reflects them. The backend route is gated by the X-Templately-Apikey
1147 - * header, so it is supplied explicitly here.
1148 - *
1149 - * Expected JSON body: { chat, detected_info: { ...fields } }
1150 - *
1151 - * @return array|\WP_Error Pass-through of the external response { status, data } or WP_Error.
1152 - */
1153 - public function update_chatbot_detected_info() {
1154 - $chat = $this->get_param('chat');
1155 - $detected_info = $this->get_param('detected_info', [], null);
1156 -
1157 - if (empty($chat)) {
1158 - return $this->error('invalid_chat_id', __('Invalid conversation ID.', 'templately'), 'ai-content/chatbot-detected-info', 400);
1159 - }
1160 -
1161 - // detected_info may arrive as a JSON string when sent via FormData.
1162 - if (is_string($detected_info)) {
1163 - $decoded = json_decode($detected_info, true);
1164 - $detected_info = is_array($decoded) ? $decoded : [];
1165 - }
1166 - if (!is_array($detected_info)) {
1167 - $detected_info = [];
1168 - }
1169 -
1170 - $extra_headers = [
1171 - 'Accept' => 'application/json',
1172 - 'X-Templately-Apikey' => $this->api_key,
1173 - ];
1174 - $response = Helper::make_api_post_request("v2/chatbot/conversation/{$chat}/detected-info", ['detected_info' => $detected_info], $extra_headers, 30);
1175 -
1176 - if (is_wp_error($response)) {
1177 - return $this->error('request_failed', __('Failed to update detected info.', 'templately'), 'ai-content/chatbot-detected-info', 500, ['error_detail' => $response->get_error_message()]);
1178 - }
1179 -
1180 - $response_code = wp_remote_retrieve_response_code($response);
1181 - $body = wp_remote_retrieve_body($response);
1182 - $data = json_decode($body, true);
1183 -
1184 - if ($response_code !== 200) {
1185 - $message = (is_array($data) && !empty($data['message'])) ? $data['message'] : sprintf(__('API returned HTTP %d error.', 'templately'), $response_code);
1186 - return $this->error('api_http_error', $message, 'ai-content/chatbot-detected-info', $response_code);
1187 - }
1188 -
1189 - if (!is_array($data) || !isset($data['status'])) {
1190 - return $this->error('invalid_response', __('Invalid response.', 'templately'), 'ai-content/chatbot-detected-info', 500);
1191 - }
1192 -
1193 - return $data;
1194 - }
1195 -
1196 - /**
1197 - * Report a completed import back to templately.dev (Phase 2 import-once gate).
1198 - *
1199 - * Once the plugin finishes importing the generated content for a conversation,
1200 - * it calls this so the backend flips the conversation status to `imported`.
1201 - * Subsequent pulls then return `already_imported = true`, and the web/plugin
1202 - * UIs refuse a second import.
1203 - *
1204 - * @return array|\WP_Error
1205 - */
1206 - public function mark_chatbot_imported() {
1207 - $chat = $this->get_param('chat');
1208 -
1209 - if (empty($chat)) {
1210 - return $this->error('invalid_chat_id', __('Invalid conversation ID.', 'templately'), 'ai-content/chatbot-mark-imported', 400);
1211 - }
1212 -
1213 - $extra_headers = [
1214 - 'Accept' => 'application/json',
1215 - 'X-Templately-Apikey' => $this->api_key,
1216 - ];
1217 - $response = Helper::make_api_post_request("v2/chatbot/conversation/{$chat}/imported", [], $extra_headers, 30);
1218 -
1219 - if (is_wp_error($response)) {
1220 - return $this->error('request_failed', __('Failed to record import.', 'templately'), 'ai-content/chatbot-mark-imported', 500, ['error_detail' => $response->get_error_message()]);
1221 - }
1222 -
1223 - $response_code = wp_remote_retrieve_response_code($response);
1224 - $body = wp_remote_retrieve_body($response);
1225 - $data = json_decode($body, true);
1226 -
1227 - if ($response_code !== 200) {
1228 - $message = (is_array($data) && !empty($data['message'])) ? $data['message'] : sprintf(__('API returned HTTP %d error.', 'templately'), $response_code);
1229 - return $this->error('api_http_error', $message, 'ai-content/chatbot-mark-imported', $response_code);
1230 - }
1231 -
1232 - if (!is_array($data) || !isset($data['status'])) {
1233 - return $this->error('invalid_response', __('Invalid response.', 'templately'), 'ai-content/chatbot-mark-imported', 500);
1234 - }
1235 -
1236 - return $data;
1237 - }
1238 -
1239 - /**
1240 - * Thin importer prepare step (Phase 2).
1241 - *
1242 - * Given a chat uuid and a session that has already been created and had its
1243 - * pack downloaded (via the existing templately_pack_create_session_and_download
1244 - * AJAX flow), this:
1245 - * 1. Registers AI process data (including `chat_id`) so ai_get_json()/
1246 - * validation keep working AND so the Finalizer's ChatAIContentProvider
1247 - * can claim this process.
1248 - * 2. Fetches the backend-generated page content for the conversation.
1249 - * 3. Writes whatever pages are ALREADY generated to the same .ai.json
1250 - * location the legacy flow uses (via AIUtils::save_template_to_file).
1251 - * 4. Downloads the signed logo URL into the WP media library (Utils::upload_logo).
1252 - *
1253 - * This endpoint NEVER waits for generation to complete. Pages still being
1254 - * generated are reported in `missing` and are pulled on demand — and waited
1255 - * for — by the Finalizer via AIContentResolver. Previously this held the
1256 - * client in a 3s poll loop until every page was ready, which delayed the
1257 - * start of the import by minutes for no benefit.
1258 - *
1259 - * It returns the resolved customization data, logo attachment and the
1260 - * process_id so the React app can build the settings FormData and run the
1261 - * existing import. No generation or local customizer is involved.
1262 - *
1263 - * Expected JSON body: { chat, session_id, ai_page_ids: { 'content/page': [...], templates: [...] } }
1264 - *
1265 - * @return array|\WP_Error
1266 - */
1267 - /**
1268 - * Does a `v2/chatbot/generated` bundle already carry every expected page?
1269 - *
1270 - * A page counts as present when it is in `templates` (string or int key, the
1271 - * upstream is inconsistent) or listed in `skipped_pages` — a skipped page is
1272 - * never coming, so waiting on it would hang the poll until it timed out.
1273 - *
1274 - * @param array $data Decoded `{ status, data }` bundle.
1275 - * @param array $expected_ids Flattened page ids, as strings.
1276 - * @return bool
1277 - */
1278 - private function is_generated_bundle_complete($data, $expected_ids) {
1279 - $generated = isset($data['data']) && is_array($data['data']) ? $data['data'] : [];
1280 -
1281 - // Never reuse a bundle the user is no longer allowed to import.
1282 - if (isset($generated['can_import']) && ! $generated['can_import']) {
1283 - return false;
1284 - }
1285 -
1286 - $templates = isset($generated['templates']) && is_array($generated['templates']) ? $generated['templates'] : [];
1287 - $skipped = isset($generated['skipped_pages']) && is_array($generated['skipped_pages']) ? array_map('strval', $generated['skipped_pages']) : [];
1288 -
1289 - if (empty($templates) && empty($skipped)) {
1290 - return false;
1291 - }
1292 -
1293 - foreach ($expected_ids as $id) {
1294 - if (array_key_exists($id, $templates) || array_key_exists((int) $id, $templates) || in_array($id, $skipped, true)) {
1295 - continue;
1296 - }
1297 - return false;
1298 - }
1299 -
1300 - return true;
1301 - }
1302 -
1303 - /**
1304 - * Resolve the conversation answers to store on a chat-driven process.
1305 - *
1306 - * Prefers what the client sent (the sidebar holds the detected info the user
1307 - * may have just edited), then what was already stored for this process (so a
1308 - * repeat call costs nothing), and only then pulls the conversation from the
1309 - * cloud — which is the path the `?process=import` landing takes, since it
1310 - * never opens the sidebar and so has no answers to send.
1311 - *
1312 - * A failure here must never break the import: it returns an empty array and
1313 - * the process is stored exactly as before.
1314 - *
1315 - * @param string $chat Conversation uuid.
1316 - * @param mixed $detected_info Raw `detected_info` sent by the client.
1317 - * @param array $ai_process_data All stored process data.
1318 - * @param string $process_id This process id.
1319 - * @return array<string,string> Map of conversation step key => value.
1320 - */
1321 - private function resolve_chat_conversation_fields($chat, $detected_info, $ai_process_data, $process_id) {
1322 - $mapped = AIUtils::map_chat_detected_info($detected_info);
1323 - if (!empty($mapped)) {
1324 - return $mapped;
1325 - }
1326 -
1327 - // Already resolved on an earlier call for this process — reuse it.
1328 - if (isset($ai_process_data[$process_id]) && AIUtils::has_conversation_data($ai_process_data[$process_id])) {
1329 - return AIUtils::map_chat_detected_info(
1330 - array_intersect_key($ai_process_data[$process_id], array_flip(AIUtils::CONVERSATION_FIELDS))
1331 - );
1332 - }
1333 -
1334 - $response = Helper::make_api_get_request("v2/chatbot/conversation/{$chat}", [], ['Accept' => 'application/json'], 30);
1335 - if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
1336 - Helper::log(sprintf('chatbot_import_prepare[%s] conversation fetch failed — process stored without answers', $chat), 'ai-import', 'warning');
1337 - return [];
1338 - }
1339 -
1340 - $data = json_decode(wp_remote_retrieve_body($response), true);
1341 - if (!is_array($data) || empty($data['data']['detected_info'])) {
1342 - return [];
1343 - }
1344 -
1345 - return AIUtils::map_chat_detected_info($data['data']['detected_info']);
1346 - }
1347 -
1348 - public function chatbot_import_prepare() {
1349 - add_filter('wp_redirect', '__return_false', 999);
1350 - set_time_limit(3 * MINUTE_IN_SECONDS);
1351 -
1352 - $handler_started = microtime(true);
1353 -
1354 - $chat = $this->get_param('chat');
1355 - $session_id = $this->get_param('session_id');
1356 - $ai_page_ids = $this->get_param('ai_page_ids', [], null);
1357 - // Conversation context, so reopening "Build with AI" later can resume this
1358 - // app-end session instead of starting from scratch. `detected_info` is
1359 - // sanitized field-by-field in AIUtils::map_chat_detected_info().
1360 - $pack_id = $this->get_param('pack_id', 0, 'absint');
1361 - $platform = $this->get_param('platform');
1362 - $detected_info = $this->get_param('detected_info', [], null);
1363 -
1364 - if (empty($chat)) {
1365 - return $this->error('invalid_chat_id', __('Invalid conversation ID.', 'templately'), 'ai-content/chatbot-import-prepare', 400);
1366 - }
1367 -
1368 - if (empty($session_id)) {
1369 - return $this->error('invalid_session_id', __('Invalid session ID.', 'templately'), 'ai-content/chatbot-import-prepare', 400);
1370 - }
1371 -
1372 - // Security: sanitize the session id before it is used to build file paths.
1373 - $session_id = AIUtils::sanitize_path_component($session_id, 'session_id');
1374 - if (is_wp_error($session_id)) {
1375 - return $this->error('invalid_session_id', $session_id->get_error_message(), 'ai-content/chatbot-import-prepare', 400);
1376 - }
1377 -
1378 - // ai_page_ids may arrive as a JSON string when sent via FormData, and with
1379 - // scalar / comma-separated group values — normalize to the canonical
1380 - // `type/sub_type => ['id',...]` shape before anything indexes into it.
1381 - $ai_page_ids = AIUtils::normalize_ai_page_ids($ai_page_ids);
1382 - if (empty($ai_page_ids)) {
1383 - return $this->error('invalid_ai_page_ids', __('Invalid AI page IDs.', 'templately'), 'ai-content/chatbot-import-prepare', 400);
1384 - }
1385 -
1386 - // Expected page ids (flattened) — the client may redirect to customization
1387 - // as soon as the home/header/footer are ready, so by import time some pages
1388 - // can still be generating. We re-pull until every expected page is present
1389 - // (bounded wait), then proceed; anything still missing falls back to the
1390 - // pack's default content.
1391 - $expected_ids = AIUtils::flatten_ai_page_ids($ai_page_ids);
1392 -
1393 - $extra_headers = ['Accept' => 'application/json'];
1394 - $cache_key = self::GENERATED_CACHE_KEY . $chat;
1395 -
1396 - // This endpoint NEVER waits for completeness. The import starts as soon as
1397 - // the session exists; whatever pages are already generated are written
1398 - // here as a warm start, and any page still generating is pulled on demand
1399 - // by the Finalizer (Core/Importer/Utils/AIContentResolver +
1400 - // Providers/ChatAIContentProvider).
1401 - //
1402 - // Reuse the bundle chatbot-generated just parked, but ONLY when it already
1403 - // holds every expected page — a complete bundle cannot become less
1404 - // complete, whereas an incomplete one has to be re-pulled to pick up the
1405 - // pages that have since finished. On the common handoff (generation
1406 - // finished long before the user landed here) this removes an entire
1407 - // duplicate transfer of every page's block JSON.
1408 - $pull_started = microtime(true);
1409 - $pull_duration = 0;
1410 - $data = Database::get_transient($cache_key);
1411 - $from_cache = is_array($data) && $this->is_generated_bundle_complete($data, $expected_ids);
1412 -
1413 - if (! $from_cache) {
1414 - // Single pull — no server-side sleep/retry. The user can reach import as
1415 - // soon as the key pages (home/header/footer) are ready while the rest are
1416 - // still generating; rather than hold the request open until everything is
1417 - // done (which tripped a gateway 504), we return a non-fatal `pending`
1418 - // status and let the client poll (JS-side pull).
1419 - $response = Helper::make_api_get_request("v2/chatbot/generated/{$chat}", [], $extra_headers, 2 * MINUTE_IN_SECONDS);
1420 - $pull_duration = microtime(true) - $pull_started;
1421 -
1422 - if (is_wp_error($response)) {
1423 - Helper::log(sprintf('chatbot_import_prepare[%s] pull failed after %.2fs: %s', $chat, $pull_duration, $response->get_error_message()), 'ai-import', 'error');
1424 - return $this->error('request_failed', __('Failed to fetch generated content.', 'templately'), 'ai-content/chatbot-import-prepare', 500, ['error_detail' => $response->get_error_message()]);
1425 - }
1426 -
1427 - $response_code = wp_remote_retrieve_response_code($response);
1428 - $data = json_decode(wp_remote_retrieve_body($response), true);
1429 -
1430 - if ($response_code !== 200 || !is_array($data) || !isset($data['status'])) {
1431 - $message = (is_array($data) && !empty($data['message'])) ? $data['message'] : sprintf(__('API returned HTTP %d error.', 'templately'), $response_code);
1432 - Helper::log(sprintf('chatbot_import_prepare[%s] pull HTTP %d after %.2fs', $chat, $response_code, $pull_duration), 'ai-import', 'error');
1433 - return $this->error('api_http_error', $message, 'ai-content/chatbot-import-prepare', $response_code ?: 500);
1434 - }
1435 -
1436 - // Park a complete bundle for the credits re-read on the success screen.
1437 - if ($this->is_generated_bundle_complete($data, $expected_ids)) {
1438 - Database::set_transient($cache_key, $data, self::GENERATED_CACHE_TTL);
1439 - }
1440 - } else {
1441 - Helper::log(sprintf('chatbot_import_prepare[%s] reused cached bundle (no upstream pull)', $chat), 'ai-import', 'info');
1442 - }
1443 -
1444 - $generated = isset($data['data']) && is_array($data['data']) ? $data['data'] : [];
1445 -
1446 - // Access gate: the backend blocks a free user past their 7-day window.
1447 - if (isset($generated['can_import']) && ! $generated['can_import']) {
1448 - 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);
1449 - }
1450 -
1451 - $templates = isset($generated['templates']) && is_array($generated['templates']) ? $generated['templates'] : [];
1452 -
1453 - // Pages the backend skipped (empty source JSON) or failed to generate.
1454 - // These will never appear in `templates`, so they must not be treated
1455 - // as "still generating" — without this, one skipped page keeps the poll
1456 - // pending until it times out.
1457 - $skipped_pages = isset($generated['skipped_pages']) && is_array($generated['skipped_pages']) ? array_map('strval', $generated['skipped_pages']) : [];
1458 - $skipped_expected = array_values(array_intersect($expected_ids, $skipped_pages));
1459 -
1460 - // Which expected pages are still missing from the bundle?
1461 - $missing = array_values(array_filter($expected_ids, function ($id) use ($templates, $skipped_pages) {
1462 - return !array_key_exists($id, $templates) && !array_key_exists((int) $id, $templates) && !in_array($id, $skipped_pages, true);
1463 - }));
1464 -
1465 - $ready = array_values(array_diff($expected_ids, $missing));
1466 - 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');
1467 -
1468 -
1469 - // Derive a process_id for this chat-driven import and register process data
1470 - // so the existing validation/ai_get_json paths keep functioning.
1471 - $process_id = 'chat-' . $session_id;
1472 - $user = $this->utils('options')->get('user');
1473 -
1474 - $ai_process_data = AIUtils::get_ai_process_data();
1475 - $record = [
1476 - 'process_id' => $process_id,
1477 - 'session_id' => $session_id,
1478 - 'ai_page_ids' => $ai_page_ids,
1479 - 'api_key' => $this->api_key,
1480 - 'user_id' => isset($user['id']) ? $user['id'] : null,
1481 - 'chat_id' => $chat,
1482 - ];
1483 -
1484 - if (!empty($pack_id)) {
1485 - $record['pack_id'] = $pack_id;
1486 - }
1487 - if (!empty($platform)) {
1488 - $record['platform'] = $platform;
1489 - }
1490 -
1491 - // Persist the app-end answers exactly as an in-plugin conversation stores
1492 - // them, so reopening "Build with AI" resumes this session instead of
1493 - // starting over. Without this the record holds no answers at all and the
1494 - // sidebar has nothing to restore.
1495 - $conversation = AIUtils::build_conversation_fields(
1496 - $this->resolve_chat_conversation_fields($chat, $detected_info, $ai_process_data, $process_id)
1497 - );
1498 - if (!empty($conversation)) {
1499 - $record = array_merge($record, $conversation);
1500 - }
1501 -
1502 - $ai_process_data[$process_id] = $record;
1503 - AIUtils::update_ai_process_data($ai_process_data);
1504 -
1505 - // Persist each generated page to its .ai.json location for the import runners.
1506 - //
1507 - // Every page present in THIS pull is written immediately, even when others
1508 - // are still generating. Holding the writes back until the whole set was
1509 - // ready meant a single slow page threw away the full bundle on every poll
1510 - // — dozens of multi-hundred-KB pulls (all of `templates`, straight off GCP)
1511 - // discarded to save nothing. Writing as we go also lets the Finalizer
1512 - // runner finalize the pages that ARE ready instead of blocking on all of
1513 - // them. Already-written pages are skipped, so a re-poll is cheap.
1514 - $save_started = microtime(true);
1515 - $saved_count = 0;
1516 - $errors = [];
1517 - $processed_pages = get_option('templately_ai_processed_pages', []);
1518 - $already_saved = isset($processed_pages[$process_id]['pages']) ? $processed_pages[$process_id]['pages'] : [];
1519 - foreach ($templates as $content_id => $template) {
1520 - if (empty($template)) {
1521 - continue;
1522 - }
1523 -
1524 - if (array_key_exists((string) $content_id, $already_saved)) {
1525 - $saved_count++;
1526 - continue;
1527 - }
1528 -
1529 - // The runners read JSON strings; normalize arrays/objects to a string.
1530 - $template_payload = is_string($template) ? $template : wp_json_encode($template);
1531 -
1532 - $result = AIUtils::save_template_to_file(
1533 - $process_id,
1534 - $session_id,
1535 - $content_id,
1536 - $template_payload,
1537 - $ai_page_ids,
1538 - false
1539 - );
1540 -
1541 - if (is_wp_error($result)) {
1542 - $errors[$content_id] = $result->get_error_message();
1543 - continue;
1544 - }
1545 - if (isset($result['status']) && $result['status'] === 'success') {
1546 - $saved_count++;
1547 - } else {
1548 - $errors[$content_id] = isset($result['message']) ? $result['message'] : 'unknown';
1549 - }
1550 - }
1551 -
1552 - // Write each backend-skipped page as an explicit `{"isSkipped": true}`
1553 - // marker (same shape the legacy per-page callback wrote) so the import
1554 - // runners fall back to the pack's default content instead of treating
1555 - // the page as missing.
1556 - $skipped_saved = [];
1557 - foreach ($skipped_expected as $skipped_id) {
1558 - if (array_key_exists($skipped_id, $templates) || array_key_exists((int) $skipped_id, $templates)) {
1559 - continue;
1560 - }
1561 -
1562 - if (array_key_exists((string) $skipped_id, $already_saved)) {
1563 - $skipped_saved[] = $skipped_id;
1564 - continue;
1565 - }
1566 -
1567 - $result = AIUtils::save_template_to_file(
1568 - $process_id,
1569 - $session_id,
1570 - $skipped_id,
1571 - '',
1572 - $ai_page_ids,
1573 - true
1574 - );
1575 -
1576 - if (is_wp_error($result)) {
1577 - $errors[$skipped_id] = $result->get_error_message();
1578 - continue;
1579 - }
1580 - if (isset($result['status']) && $result['status'] === 'success') {
1581 - $skipped_saved[] = $skipped_id;
1582 - } else {
1583 - $errors[$skipped_id] = isset($result['message']) ? $result['message'] : 'unknown';
1584 - }
1585 - }
1586 -
1587 - $save_duration = microtime(true) - $save_started;
1588 - 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');
1589 -
1590 - // NOTE: there is deliberately NO `pending` return here any more. Pages that
1591 - // are still generating come back in `missing` and are pulled on demand —
1592 - // and waited for — by the Finalizer. Returning `pending` made the client
1593 - // poll for minutes before the import could even start.
1594 - //
1595 - // NOT an error when nothing was saved: with the wait deferred to the
1596 - // Finalizer it is legitimate for zero pages to be ready at import start.
1597 - // Only a genuine write failure (something was ready but every save
1598 - // errored) is fatal.
1599 - if ($saved_count === 0 && empty($skipped_saved) && !empty($errors)) {
1600 - return $this->error('save_failed', __('Failed to save generated content.', 'templately'), 'ai-content/chatbot-import-prepare', 500, ['errors' => $errors]);
1601 - }
1602 -
1603 - Helper::log(sprintf('chatbot_import_prepare[%s] returning: pages=%d missing=%d pull=%.2fs', $chat, count($templates), count($missing), $pull_duration), 'ai-import', 'info');
1604 -
1605 - // Import the logo into the media library and map it into the customization.
1606 - $customization = isset($generated['customization_data']) && is_array($generated['customization_data']) ? $generated['customization_data'] : [];
1607 - $logo = null;
1608 - $logo_url = !empty($generated['logo_url']) ? esc_url_raw($generated['logo_url']) : '';
1609 -
1610 - if (!empty($logo_url)) {
1611 - $logo_started = microtime(true);
1612 - $uploaded = Utils::upload_logo($logo_url, $session_id);
1613 - Helper::log(sprintf('chatbot_import_prepare[%s] logo upload in %.2fs', $chat, microtime(true) - $logo_started), 'ai-import', 'info');
1614 - if (!empty($uploaded['id'])) {
1615 - $logo = [
1616 - 'id' => (int) $uploaded['id'],
1617 - 'url' => $uploaded['url'],
1618 - ];
1619 - } elseif (!empty($uploaded['error'])) {
1620 - // Logo is non-fatal: log and continue without it.
1621 - Helper::log('chatbot_import_prepare logo upload failed: ' . $uploaded['error']);
1622 - }
1623 - }
1624 -
1625 - // Reflect the imported logo back into the customization payload so React
1626 - // can build the settings FormData from a single source.
1627 - if (!empty($logo)) {
1628 - $customization['logo'] = $logo;
1629 - }
1630 -
1631 - Helper::log(sprintf('chatbot_import_prepare[%s] done in %.2fs total', $chat, microtime(true) - $handler_started), 'ai-import', 'info');
1632 -
1633 - return [
1634 - 'status' => 'success',
1635 - 'data' => [
1636 - 'session_id' => $session_id,
1637 - 'process_id' => $process_id,
1638 - 'ai_page_ids' => $ai_page_ids,
1639 - 'saved' => $saved_count,
1640 - // Pages the backend explicitly skipped — imported with the
1641 - // pack's default content instead.
1642 - 'skipped' => $skipped_expected,
1643 - // Readiness snapshot at import start. `missing` pages are NOT a
1644 - // failure: the Finalizer pulls each on demand and waits for it.
1645 - 'expected' => $expected_ids,
1646 - 'ready' => $ready,
1647 - 'missing' => $missing,
1648 - 'platform' => isset($customization['platform']) ? $customization['platform'] : null,
1649 - 'customization_data' => $customization,
1650 - 'logo' => $logo,
1651 - 'errors' => $errors,
1652 - ],
1653 - ];
1654 - }
1655 -
1656 - /**
1657 - * Validate API key against database
1658 - * Checks if the provided API key exists for any user on the current site
1659 - * Handles both single-site and multisite WordPress installations
1660 - *
1661 - * @param string $api_key The API key to validate
1662 - * @return bool True if valid, false otherwise
1663 - */
1664 - private function validate_api_key_in_db($api_key) {
1665 - global $wpdb;
1666 -
1667 - $api_key = sanitize_text_field($api_key);
1668 -
1669 - if (empty($api_key)) {
1670 - return false;
1671 - }
1672 -
1673 - $meta_key = '_templately_api_key';
1674 -
1675 - // Handle multisite: key will have site prefix in multisite
1676 - if (is_multisite()) {
1677 - // get_user_option() uses the format: {$wpdb->base_prefix}{$blog_id}_{$meta_key}
1678 - // For current blog, we need to check with the current blog prefix
1679 - $blog_id = get_current_blog_id();
1680 - $meta_key = $wpdb->get_blog_prefix($blog_id) . $meta_key;
1681 - }
1682 -
1683 - // Query to check if this API key exists for any user
1684 - $query = $wpdb->prepare(
1685 - "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value = %s LIMIT 1",
1686 - $meta_key,
1687 - $api_key
1688 - );
1689 -
1690 - $user_id = $wpdb->get_var($query);
1691 -
1692 - return !empty($user_id);
399 + private function get_api_url($end_point): string {
400 + $dev_mode = defined('TEMPLATELY_DEV') && TEMPLATELY_DEV;
401 + return $dev_mode ? "https://app.templately.dev/api/v2/" . $end_point : "https://app.templately.com/api/v2/" . $end_point;
1693 402 }
1694 403 }