PluginProbe
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! / 3.3.0
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! v3.3.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.3.0, at includes/API/AIContent.php

402 lines 13.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 Templately\Utils\Helper;
14 use WP_REST_Request;
15 use Templately\Core\Importer\Utils\Utils;
16 use Templately\Core\Importer\Utils\AIUtils;
17
18 class AIContent extends API {
19 private $endpoint = 'ai-content';
20 private $dev_mode = false;
21
22
23 /**
24 * AIContent constructor.
25 *
26 * @param string $file File path.
27 * @param array $settings Settings.
28 */
29 public function __construct() {
30 $this->dev_mode = (defined('TEMPLATELY_DEV') && TEMPLATELY_DEV) || (defined('IMPORT_DEBUG') && IMPORT_DEBUG);
31
32 parent::__construct();
33
34 }
35
36 public function _permission_check(WP_REST_Request $request) {
37 $this->request = $request;
38 $process_id = $this->get_param('process_id');
39
40 $_route = $request->get_route();
41 if ('/templately/v1/ai-content/ai-update' === $_route || '/templately/v1/ai-content/ai-update-preview' === $_route) {
42 if (empty($process_id)) {
43 return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'calculate_credit', 400);
44 }
45
46 // Check AI process data using API key-based storage
47 $ai_process_data = AIUtils::get_ai_process_data();
48 if (is_array($ai_process_data) && !empty($ai_process_data[$process_id])) {
49 return true;
50 }
51
52 return (bool) Helper::get_matched_session_data($process_id);
53 }
54
55 return parent::permission_check($request);
56 }
57
58
59 public function register_routes() {
60 // $this->get( $this->endpoint . '/calculate-credit', [ $this, 'calculate_credit' ] );
61 $this->post($this->endpoint . '/modify-content', [$this, 'modify_content']);
62 $this->post($this->endpoint . '/ai-update', [$this, 'ai_update']);
63 $this->post($this->endpoint . '/ai-update-preview', [$this, 'ai_update_preview']);
64 // die(rest_url( 'templately/v1/ai-content/ai-update' ));
65 }
66
67 public function calculate_credit() {
68 $pack_id = $this->get_param('pack_id');
69
70 return [
71 'status' => 'success',
72 'data' => [
73 'availableCredit' => 100,
74 ],
75 ];
76
77 if (empty($pack_id)) {
78 return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'calculate_credit', 400);
79 }
80
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 ]);
92
93
94 // return $response;
95 if (is_wp_error($response)) {
96 return $this->error('request_failed', __('Request failed.', 'templately'), 'calculate_credit', 500, $response);
97 }
98
99 $body = wp_remote_retrieve_body($response);
100 $data = json_decode($body, true);
101 // error status is ok
102 if (! is_array($data) || ! isset($data['status'])) {
103 return $this->error('invalid_response', __('Invalid response.', 'templately'), 'calculate_credit', 500);
104 }
105
106
107 return $data;
108 }
109
110 public function modify_content() {
111 add_filter('wp_redirect', '__return_false', 999);
112 set_time_limit(3 * MINUTE_IN_SECONDS);
113 ini_set('max_execution_time', 3 * MINUTE_IN_SECONDS);
114
115 $pack_id = $this->get_param('pack_id');
116 $isBusinessNichesNew = $this->get_param('isBusinessNichesNew', false);
117 $ai_page_ids = $this->get_param('ai_page_ids', [], null);
118 $content_ids = $this->get_param('content_ids', [], null);
119 $session_id = $this->get_param('session_id'); // Add session_id parameter
120 $preview_pages = $this->get_param('preview_pages', [], null);
121 $platform = $this->get_param('platform');
122
123 // ai content fields
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');
131
132 if (empty($pack_id)) {
133 return $this->error('invalid_id', __('Invalid ID.', 'templately'), 'modify_content', 400);
134 }
135 if (empty($category)) {
136 return $this->error('invalid_prompt', __('Invalid prompt.', 'templately'), 'modify_content', 400);
137 }
138 if (empty($content_ids) && empty($preview_pages)) {
139 return $this->error('invalid_content_ids', __('Invalid content ids.', 'templately'), 'modify_content', 400);
140 }
141 if (empty($platform)) {
142 return $this->error('invalid_platform', __('Invalid platform.', 'templately'), 'modify_content', 400);
143 }
144
145
146 // $response = get_transient( '__templately_ai_process_id' );
147
148 // if(empty($response)) {
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 ],
159 'body' => json_encode([
160 'business_name' => $name,
161 'business_niches' => $category,
162 'prompt' => $description,
163 'email' => $email,
164 'phone' => $contactNumber,
165 'address' => $businessAddress,
166 'openingHour' => $openingHour,
167 'pack_id' => $pack_id,
168 'content_ids' => $content_ids,
169 'platform' => $platform,
170 'preview_pages' => $preview_pages,
171 'callback' => defined('TEMPLATELY_CALLBACK') ? TEMPLATELY_CALLBACK . '/wp-json/templately/v1/ai-content/ai-update' : rest_url('templately/v1/ai-content/ai-update'),
172 ]),
173 ]);
174
175 // set_transient( '__templately_ai_process_id', $response, 60 * 60 * 24 * 30 );
176 // }
177
178 $bk_ai_business_niches = get_option('templately_ai_business_niches', []);
179 if (!empty($business_niches) && $isBusinessNichesNew && ! in_array($business_niches, $bk_ai_business_niches)) {
180 $bk_ai_business_niches[] = $business_niches;
181 update_option('templately_ai_business_niches', $bk_ai_business_niches, false);
182 }
183
184 // return $response;
185 if (is_wp_error($response)) {
186 error_log(print_r($response, true));
187 return $this->error('request_failed', __('Request failed.', 'templately'), 'modify_content', 500, $response->additional_data);
188 }
189
190 $body = wp_remote_retrieve_body($response);
191 $data = json_decode($body, true);
192 // error status is ok, if status is error then return as is
193 if (! is_array($data) || ! isset($data['status'])) {
194 return $this->error('invalid_response', __('Invalid response.', 'templately'), 'modify_content', 500, $data);
195 }
196
197 // "{"status":"success","message":"The content is being generated in the queue","process_id":"01JRQQD39GNWTNF18EWF8YH0BG-271838-pack-408"}"
198 if (isset($data['status']) && $data['status'] === 'success' && isset($data['process_id'])) {
199 $process_id = $data['process_id'];
200
201 // Save templates to files if available using the common function
202 if (!empty($data['templates']) && is_array($data['templates'])) {
203 foreach ($data['templates'] as $content_id => $template_data) {
204 // Decode template if it's base64 encoded
205 if (! empty($template_data) && base64_decode($template_data, true) !== false) {
206 $data['templates'][$content_id] = base64_decode($template_data);
207 }
208
209 if (!empty($template_data)) {
210 Helper::save_template_to_file(
211 $process_id,
212 $content_id,
213 $template_data,
214 $ai_page_ids,
215 true, // Always use preview mode for AI content workflow
216 isset($template_data['isSkipped']) ? $template_data['isSkipped'] : false
217 );
218 }
219 }
220 }
221
222 $ai_process_data[$process_id] = [
223 'name' => $name,
224 'category' => $category,
225 'description' => $description,
226 'email' => $email,
227 'contactNumber' => $contactNumber,
228 'businessAddress' => $businessAddress,
229 'openingHour' => $openingHour,
230 'process_id' => $process_id,
231 'pack_id' => $pack_id,
232 'ai_page_ids' => $ai_page_ids,
233 'ai_preview_ids' => $preview_pages,
234 'content_ids' => $content_ids,
235 'platform' => $platform,
236 'api_key' => $this->api_key,
237 'session_id' => $session_id, // Store session_id for coordination
238 ];
239
240 // Update using API key-based storage with automatic count-based cleanup
241 AIUtils::update_ai_process_data($ai_process_data);
242
243 return [
244 'status' => 'success',
245 'message' => __('The content is being generated in the queue', 'templately'),
246 'process_id' => $process_id,
247 'templates' => !empty($data['templates']) ? $data['templates'] : null,
248 ];
249 }
250
251 return $data;
252 }
253
254 public function ai_update() {
255 add_filter('wp_redirect', '__return_false', 999);
256
257 $template = $this->get_param('template');
258 $process_id = $this->get_param('process_id');
259 $template_id = $this->get_param('template_id');
260 $content_id = $this->get_param('content_id');
261 $type = $this->get_param('type');
262 $isSkipped = $this->get_param('isSkipped', false);
263 $credit_cost = $this->request->get_param('credit_cost');
264
265 error_log('process_id: ' . $process_id);
266
267 // Handle credit cost updates separately
268 if ($this->request->has_param('credit_cost')) {
269 $processed_pages = get_option("templately_ai_processed_pages", []);
270 $processed_pages[$process_id] = $processed_pages[$process_id] ?? [];
271 $processed_pages[$process_id]['credit_cost'] = $credit_cost;
272 update_option("templately_ai_processed_pages", $processed_pages, false);
273
274 return [
275 'status' => 'success',
276 'data' => [
277 'process_id' => $process_id,
278 'credit_cost' => $credit_cost,
279 ],
280 ];
281 }
282
283 // Always use preview mode for AI content workflow
284 // Get AI process data using API key-based storage
285 $ai_process_data = AIUtils::get_ai_process_data();
286
287 if (empty($ai_process_data[$process_id]['ai_page_ids'])) {
288 return $this->error('invalid_process_id', __('Invalid process id.', 'templately'), 'ai-content/ai-update', 400);
289 }
290
291 $ai_page_ids = $ai_process_data[$process_id]['ai_page_ids'];
292
293 // Use the common helper function to save the template (always preview mode)
294 $result = Helper::save_template_to_file(
295 $process_id,
296 $content_id,
297 $template,
298 $ai_page_ids,
299 true, // Always use preview mode
300 $isSkipped
301 );
302
303 if(is_wp_error($result)){
304 return $result;
305 }
306
307 // Return the result from the helper function
308 if (isset($result['status']) && $result['status'] === 'success') {
309 return $result;
310 }
311
312 // Return error if the helper function failed
313 return $result;
314 }
315
316 public function ai_update_preview() {
317 add_filter('wp_redirect', '__return_false', 999);
318
319 $template = $this->get_param('templates'); // Now expects an array with content_id as keys
320 $process_id = $this->get_param('process_id');
321 $isSkipped = $this->get_param('isSkipped', false);
322 $error = $this->get_param('error', null);
323
324 error_log('process_id: ' . $process_id);
325
326 if (!empty($isSkipped) || !empty($error)) {
327 // Update AI process data with error using API key-based storage
328 $ai_process_data = AIUtils::get_ai_process_data();
329 if (isset($ai_process_data[$process_id])) {
330 $ai_process_data[$process_id]['preview_error'] = $error;
331 AIUtils::update_ai_process_data($ai_process_data);
332 }
333 wp_send_json_error([
334 'status' => 'error',
335 'message' => $error,
336 ]);
337 }
338
339 // Validate template parameter is an array
340 if (!is_array($template) || empty($template)) {
341 return $this->error('invalid_template', __('Template must be a non-empty array with content_id as keys.', 'templately'), 'ai-content/ai-update-preview', 400);
342 }
343
344 // Always use preview mode for AI content workflow
345 // Get AI process data using API key-based storage
346 $ai_process_data = AIUtils::get_ai_process_data();
347
348 if (empty($ai_process_data[$process_id]['ai_page_ids'])) {
349 return $this->error('invalid_process_id', __('Invalid process id.', 'templately'), 'ai-content/ai-update-preview', 400);
350 }
351
352 $ai_page_ids = $ai_process_data[$process_id]['ai_page_ids'];
353 $results = [];
354 $success_count = 0;
355 $error_count = 0;
356
357 // Process each content_id/template pair
358 foreach ($template as $content_id => $template_data) {
359 // Use the common helper function to save the template (always preview mode)
360 $result = Helper::save_template_to_file(
361 $process_id,
362 $content_id,
363 $template_data,
364 $ai_page_ids,
365 true, // Always use preview mode
366 $isSkipped
367 );
368
369 $results[$content_id] = $result;
370
371 // Track success/error counts
372 if (isset($result['status']) && $result['status'] === 'success') {
373 $success_count++;
374 } else {
375 $error_count++;
376 }
377 }
378
379 // Return consolidated response
380 $overall_status = $error_count === 0 ? 'success' : ($success_count === 0 ? 'error' : 'partial_success');
381
382 // Note: No cleanup needed with API key-based storage and count-based management
383
384 return [
385 'status' => $overall_status,
386 'message' => sprintf(
387 __('Processed %d templates: %d successful, %d failed.', 'templately'),
388 count($template),
389 $success_count,
390 $error_count
391 ),
392 ];
393 }
394
395
396
397 private function get_api_url($end_point): string {
398 $dev_mode = defined('TEMPLATELY_DEV') && TEMPLATELY_DEV;
399 return $dev_mode ? "https://app.templately.dev/api/v2/" . $end_point : "https://app.templately.com/api/v2/" . $end_point;
400 }
401 }
402