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/Utils/Helper.php +98 -466 3.7.33.3.3 View file →
@@ -17,18 +17,8 @@
17 17 * @since 1.0.0
18 18 */
19 19 class Helper extends Base {
20 20 /**
21 - * Check if development API should be used
22 - *
23 - * @return bool True if development API should be used
24 - */
25 - public static function is_dev_api(){
26 - // Only check TEMPLATELY_DEV_API constant - no fallback mechanisms
27 - return defined( 'TEMPLATELY_DEV_API' ) && constant( 'TEMPLATELY_DEV_API' );
28 - }
29 -
30 - /**
31 21 * Get installed WordPress Plugin List
32 22 * @return array
33 23 */
34 24 public static function get_plugins() {
@@ -56,49 +46,24 @@
56 46
57 47 /**
58 48 * Collect IP from request.
59 49 *
60 - * Prefers REMOTE_ADDR since it cannot be spoofed by the client. When it is
61 - * a private/reserved address (reverse proxy, Docker bridge gateway like
62 - * 192.168.65.1, local dev), the forwarded headers are scanned for the first
63 - * public IP. If nothing public is found, the request is local: 127.0.0.1.
64 - *
65 50 * @return string
66 51 */
67 52 public static function get_ip() {
68 - $remote_addr = ! empty($_SERVER['REMOTE_ADDR']) ? sanitize_text_field($_SERVER['REMOTE_ADDR']) : '';
69 -
70 - if (self::is_public_ip($remote_addr)) {
71 - return $remote_addr;
53 + $ip = '127.0.0.1'; // Local IP
54 + if (! empty($_SERVER['HTTP_CLIENT_IP'])) {
55 + $ip = $_SERVER['HTTP_CLIENT_IP'];
56 + } elseif (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
57 + $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
58 + } else {
59 + $ip = ! empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : $ip;
72 60 }
73 61
74 - foreach (['HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP'] as $header) {
75 - if (empty($_SERVER[$header])) {
76 - continue;
77 - }
78 - $candidates = explode(',', sanitize_text_field($_SERVER[$header]));
79 - foreach ($candidates as $candidate) {
80 - $candidate = trim($candidate);
81 - if (self::is_public_ip($candidate)) {
82 - return $candidate;
83 - }
84 - }
85 - }
86 -
87 - return '127.0.0.1';
62 + return sanitize_text_field($ip);
88 63 }
89 64
90 65 /**
91 - * Check whether a string is a valid public (non-private, non-reserved) IP.
92 - *
93 - * @param string $ip
94 - * @return bool
95 - */
96 - private static function is_public_ip($ip): bool {
97 - return (bool) filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
98 - }
99 -
100 - /**
101 66 * Get views for front-end display
102 67 *
103 68 * @param string $name it will be file name only from the view's folder.
104 69 * @param array $data
@@ -114,153 +79,8 @@
114 79 }
115 80 }
116 81
117 82 /**
118 - * A URL on the public Templately website, honouring the dev domain.
119 - *
120 - * The PHP counterpart of `react-src/utils/helper.js#webURL`. A hard-coded
121 - * `https://templately.com/...` sends a site running against the dev API to
122 - * the live site, where its account does not exist — so build every out-link
123 - * through this instead.
124 - *
125 - * Note this is the *website*, not the API host `get_api_url()` builds.
126 - *
127 - * @param string $path Path with or without a leading slash.
128 - * @param array $args Query args (utm_* etc).
129 - * @return string
130 - */
131 - public static function web_url( string $path = '', array $args = [] ): string {
132 - $base_url = self::is_dev_api() ? 'https://templately.dev' : 'https://templately.com';
133 - $url = $base_url . '/' . ltrim( $path, '/' );
134 -
135 - return empty( $args ) ? $url : add_query_arg( $args, $url );
136 - }
137 -
138 - /**
139 - * Get API URL for Templately endpoints
140 - *
141 - * @param string $endpoint API endpoint path (e.g., 'v2/import/pack/123')
142 - * @return string Complete API URL
143 - */
144 - public static function get_api_url($endpoint): string {
145 - $base_url = self::is_dev_api() ? 'https://app.templately.dev' : 'https://app.templately.com';
146 -
147 - /**
148 - * Filter the base URL for development API
149 - *
150 - * @since 3.5.0
151 - * @param string $base_url The default base URL
152 - */
153 - $base_url = apply_filters('templately_dev_api_base_url', $base_url);
154 -
155 - return "{$base_url}/api/{$endpoint}";
156 - }
157 -
158 - /**
159 - * Make a unified API request to Templately API
160 - *
161 - * @param string $method HTTP method (GET or POST)
162 - * @param string $api_url Complete API URL
163 - * @param array $body Request body data (for POST requests)
164 - * @param array $extra_headers Additional headers beyond the standard ones
165 - * @param int $timeout Request timeout in seconds (default: 30)
166 - * @return array|WP_Error Response array or WP_Error on failure
167 - */
168 - private static function make_api_request($method, $api_url, $body = [], $extra_headers = [], $timeout = 30) {
169 - $api_key = Options::get_instance()->get('api_key');
170 -
171 - $headers = [
172 - 'Authorization' => 'Bearer ' . $api_key,
173 - 'x-templately-ip' => self::get_ip(),
174 - 'x-templately-url' => home_url('/'),
175 - 'x-templately-version' => defined( 'TEMPLATELY_VERSION' ) ? constant( 'TEMPLATELY_VERSION' ) : '1.0.0',
176 - // Force JSON responses so the cloud returns JSON errors instead of an HTML
177 - // error page (which json_decode() cannot parse). Binary/XML downloads
178 - // (zip pack, attachment WXR) use their own wp_remote_* calls and bypass
179 - // this helper, so they are unaffected. Callers can override via $extra_headers.
180 - 'Accept' => 'application/json',
181 - ];
182 -
183 - // Add Content-Type for POST requests
184 - if (strtoupper($method) === 'POST') {
185 - $headers['Content-Type'] = 'application/json';
186 - }
187 -
188 - // Resolve requested platform: $_REQUEST wins (frontend-supplied), then caller's extra_headers, then default.
189 - if ( isset( $_REQUEST['requested_platform'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
190 - $extra_headers['x-templately-requested-platform'] = sanitize_text_field( wp_unslash( $_REQUEST['requested_platform'] ) );
191 - } elseif ( ! isset( $extra_headers['x-templately-requested-platform'] ) ) {
192 - $extra_headers['x-templately-requested-platform'] = 'templately';
193 - }
194 -
195 - // Merge additional headers
196 - $headers = array_merge($headers, $extra_headers);
197 -
198 - $args = [
199 - 'timeout' => $timeout,
200 - 'headers' => $headers,
201 - ];
202 -
203 - // Apply filter to allow network admin or other functionality to modify request args
204 - $args = apply_filters( 'templately_api_request_params', $args, $method, $api_url );
205 -
206 - // Add body for POST requests
207 - if (strtoupper($method) === 'POST') {
208 - $args['body'] = is_array($body) ? json_encode($body) : $body;
209 - }
210 -
211 - // Make the appropriate request
212 - if (strtoupper($method) === 'POST') {
213 - $response = wp_remote_post($api_url, $args);
214 - } else {
215 - $response = wp_remote_get($api_url, $args);
216 - }
217 -
218 - // Check for verification header in the response
219 - self::check_verification_header($response);
220 -
221 -
222 - // Check for site disconnection in response body
223 - self::check_site_disconnection($response);
224 -
225 - return $response;
226 - }
227 -
228 - /**
229 - * Make a GET request to Templately API
230 - *
231 - * @param string $endpoint API endpoint path (e.g., 'v2/import/pack/123')
232 - * @param array $query_params Query parameters as key-value pairs
233 - * @param array $extra_headers Additional headers beyond the standard ones
234 - * @param int $timeout Request timeout in seconds (default: 30)
235 - * @return array|WP_Error Response array or WP_Error on failure
236 - */
237 - public static function make_api_get_request($endpoint, $query_params = [], $extra_headers = [], $timeout = 30) {
238 - $api_url = self::get_api_url($endpoint);
239 -
240 - // Add query parameters if provided
241 - if (!empty($query_params)) {
242 - $api_url = add_query_arg($query_params, $api_url);
243 - }
244 -
245 - return self::make_api_request('GET', $api_url, [], $extra_headers, $timeout);
246 - }
247 -
248 - /**
249 - * Make a POST request to Templately API
250 - *
251 - * @param string $endpoint API endpoint path (e.g., 'v2/feedback/store')
252 - * @param array $body Request body data
253 - * @param array $extra_headers Additional headers beyond the standard ones
254 - * @param int $timeout Request timeout in seconds (default: 30)
255 - * @return array|WP_Error Response array or WP_Error on failure
256 - */
257 - public static function make_api_post_request($endpoint, $body = [], $extra_headers = [], $timeout = 30) {
258 - $api_url = self::get_api_url($endpoint);
259 - return self::make_api_request('POST', $api_url, $body, $extra_headers, $timeout);
260 - }
261 -
262 - /**
263 83 * Sanitize Helper
264 84 *
265 85 * @param mixed $value
266 86 * @param string $type
@@ -280,194 +100,8 @@
280 100 return $sanitized_value;
281 101 }
282 102
283 103 /**
284 - * Escape a string for safe embedding inside a GraphQL or JSON string literal.
285 - *
286 - * GraphQL string escaping rules are identical to JSON string escaping (per the
287 - * GraphQL spec), so wp_json_encode() is the authoritative escaper. We strip the
288 - * outer quotes it adds and return only the escaped inner content, ready to be
289 - * wrapped in your own quote pair.
290 - *
291 - * Handles pre-encoded JSON: when the caller has already run json_encode() +
292 - * wp_slash() on a value (e.g. categories, dependencies in Items.php), the
293 - * quotes are already escaped as \" and the string is ready to embed. Calling
294 - * wp_json_encode() again would double-escape those backslashes. We detect this
295 - * case by checking whether wp_unslash() produces valid JSON, and if so, return
296 - * the value directly without further encoding.
297 - *
298 - * @param string $value Raw string or wp_slash(json_encode()) output.
299 - * @return string Escaped string, safe to place between double quotes in GraphQL/JSON.
300 - */
301 - public static function esc_json_string( $value ) {
302 - $value = (string) $value;
303 -
304 - // If wp_slash() was applied to a JSON string upstream, the quotes are
305 - // already escaped (e.g. {\"key\":\"val\"}). Detect this by unslashing and
306 - // checking for valid JSON — if it matches, the value is already suitable
307 - // for embedding in a string literal; return it as-is to avoid doubling backslashes.
308 - $unslashed = wp_unslash( $value );
309 - if ( $unslashed !== $value ) {
310 - $decoded = json_decode( $unslashed, true );
311 - if ( json_last_error() === JSON_ERROR_NONE && null !== $decoded ) {
312 - return $value;
313 - }
314 - }
315 -
316 - $encoded = wp_json_encode( $value );
317 - // wp_json_encode wraps the value in "...", strip those outer quotes.
318 - return substr( $encoded, 1, -1 );
319 - }
320 -
321 - /**
322 - * Check for X-Templately-Verified header and update user verification status
323 - *
324 - * @param array|WP_Error $response The HTTP response array from wp_remote_get/wp_remote_post
325 - * @return void
326 - */
327 - public static function check_verification_header($response) {
328 - // Only process if response is not a WP_Error and contains headers
329 - if (is_wp_error($response)) {
330 - return;
331 - }
332 -
333 - // Retrieve the X-Templately-Verified header
334 - $verification_header = wp_remote_retrieve_header($response, 'X-Templately-Verified');
335 -
336 - // Check if header exists and has a truthy value
337 - if (!empty($verification_header) && filter_var($verification_header, FILTER_VALIDATE_BOOLEAN)) {
338 - try {
339 - // Get current user data
340 - $options = Options::get_instance();
341 - $user = $options->get('user');
342 -
343 - // Only update if user data exists and is not already verified
344 - if (!empty($user) && is_array($user) && empty($user['is_verified'])) {
345 - // Set verification flag
346 - $user['is_verified'] = true;
347 -
348 - // Save updated user data
349 - $options->set('user', $user);
350 -
351 - }
352 -
353 - if (!empty($user['is_verified'])){
354 - if(!headers_sent()){
355 - header( 'X-Templately-Verified: true' );
356 - if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
357 - self::log('User verification status already updated via X-Templately-Verified header');
358 - }
359 - }
360 -
361 - return true;
362 - }
363 - } catch (\Exception $e) {
364 - // Log error if debug logging is enabled
365 - if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
366 - self::log('Error updating user verification status: ' . $e->getMessage());
367 - }
368 - }
369 - }
370 -
371 - return false;
372 - }
373 -
374 - /**
375 - * Check for site disconnection status in API response body
376 - *
377 - * Detects SiteNotConnected errors and updates user disconnection status.
378 - * Sends X-Templately-Disconnected header for frontend detection.
379 - *
380 - *
381 - * @param array|WP_Error|mixed $response The response object or body array
382 - * @return bool True if site is disconnected, false otherwise
383 - */
384 - public static function check_site_disconnection($response) {
385 - if (is_wp_error($response)) {
386 - return false;
387 - }
388 -
389 - $response_body = $response;
390 -
391 - // If it's a raw WP response array with body, decode it
392 - if (is_array($response) && isset($response['body']) && is_string($response['body'])) {
393 - $response_body = json_decode(wp_remote_retrieve_body($response), true);
394 - }
395 -
396 - // Check if response body indicates site disconnection
397 - if (!is_array($response_body)) {
398 - return false;
399 - }
400 -
401 - $status = $response_body['status'] ?? null;
402 - $status_text = $response_body['statusText'] ?? null;
403 -
404 - // Check for SiteNotConnected error
405 - if ($status === 'error' && $status_text === 'SiteNotConnected') {
406 - try {
407 - // Get current user data
408 - $options = Options::get_instance();
409 - $user = $options->get('user');
410 -
411 - // Only update if user data exists
412 - if (!empty($user) && is_array($user)) {
413 - // Set disconnection flag
414 - $user['is_disconnected'] = true;
415 -
416 - // Save updated user data
417 - $options->set('user', $user);
418 -
419 - if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
420 - self::log('Site disconnection detected: SiteNotConnected status');
421 - }
422 - }
423 -
424 - // Send header for frontend detection
425 - if (!headers_sent()) {
426 - header('X-Templately-Disconnected: true');
427 - }
428 -
429 - return true;
430 - } catch (\Exception $e) {
431 - // Log error if debug logging is enabled
432 - if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
433 - self::log('Error updating site disconnection status: ' . $e->getMessage());
434 - }
435 - }
436 - }
437 -
438 - return false;
439 - }
440 -
441 - /**
442 - * Clear site disconnection status
443 - *
444 - * Called after successful site migration to reset the disconnection flag.
445 - *
446 - * @return void
447 - */
448 - public static function clear_site_disconnection() {
449 - try {
450 - $options = Options::get_instance();
451 - $user = $options->get('user');
452 -
453 - if (!empty($user) && is_array($user)) {
454 - $user['site_url'] = base64_encode( home_url('/') );
455 - $user['is_disconnected'] = false;
456 - $options->set('user', $user);
457 -
458 - if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
459 - self::log('Site disconnection status cleared and URL updated.');
460 - }
461 - }
462 - } catch (\Exception $e) {
463 - if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
464 - self::log('Error clearing site disconnection status: ' . $e->getMessage());
465 - }
466 - }
467 - }
468 -
469 - /**
470 104 * API Error Formatter
471 105 *
472 106 * @param int $error_code
473 107 * @param mixed $error_message
@@ -561,59 +195,21 @@
561 195
562 196 /**
563 197 * Printing Error Logs in debug.log file.
564 198 *
565 - * @param mixed $log The data to log
566 - * @param string $context Optional context for categorizing log entries
567 - * @param string $level Optional log level (debug, info, warning, error)
199 + * @param mixed $log
568 200 * @return void
569 201 */
570 - public static function log($log, $context = '', $level = 'info') {
571 - // Allow complete override of logging behavior
572 - $override_result = apply_filters('templately_log_override', null, $log, $context, $level);
573 - if ($override_result !== null) {
574 - return;
202 + public static function log($log) {
203 + if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
204 + if (is_array($log) || is_object($log)) {
205 + error_log(print_r($log, true));
206 + } else {
207 + error_log($log ?: '');
208 + }
575 209 }
576 -
577 - // Only log if WP_DEBUG_LOG is enabled
578 - if (!defined('WP_DEBUG_LOG') || !WP_DEBUG_LOG) {
579 - return;
580 - }
581 -
582 - // Format the log message
583 - $formatted_message = self::format_log_message($log, $context, $level);
584 -
585 - // Write to error log
586 - error_log($formatted_message);
587 210 }
588 211
589 - /**
590 - * Format log message with context and level
591 - *
592 - * @param mixed $log The data to log
593 - * @param string $context Context for categorizing log entries
594 - * @param string $level Log level
595 - * @return string Formatted log message
596 - */
597 - private static function format_log_message($log, $context = '', $level = 'info') {
598 - // Convert arrays and objects to readable format
599 - if (is_array($log) || is_object($log)) {
600 - $log_content = print_r($log, true);
601 - } else {
602 - $log_content = (string) ($log ?: '');
603 - }
604 -
605 - // Build the formatted message
606 - $timestamp = current_time('Y-m-d H:i:s');
607 - $level_upper = strtoupper($level);
608 -
609 - if (!empty($context)) {
610 - return "[{$timestamp}] [{$level_upper}] [{$context}] {$log_content}";
611 - } else {
612 - return "[{$timestamp}] [{$level_upper}] {$log_content}";
613 - }
614 - }
615 -
616 212 public static function should_flush() {
617 213 if (isset($_REQUEST['is_lightspeed']) && $_REQUEST['is_lightspeed'] === 'true') {
618 214 return false;
619 215 }
@@ -728,9 +324,9 @@
728 324 */
729 325 public static function enable_elementor_container() {
730 326 if (class_exists('Elementor\Plugin')) {
731 327 $control_name = Plugin::instance()->experiments->get_feature_option_key('container');
732 - if (get_option($control_name) !== 'active') {
328 + if (get_option($control_name) === 'inactive') {
733 329 update_option($control_name, 'active');
734 330 return true;
735 331 }
736 332 }
@@ -771,71 +367,107 @@
771 367 return $r;
772 368 }
773 369
774 370 /**
775 - * Creates the plugin's working directory under wp-uploads and blocks direct
776 - * web access to it.
371 + * Save template data to file
777 372 *
778 - * Everything the importer needs on disk lands here: the extracted pack (its
779 - * WXR, its template JSON, its attachments), the AI-generated page JSON, and
780 - * the FSI logs. wp-uploads is web-served, so these paths are not private just
781 - * because their session id is a uuid — the guards are what makes them
782 - * unreadable, not the name.
373 + * Common function for saving templates to files, used by AI content operations
783 374 *
784 - * .htaccess covers Apache and is inherited by everything below this point;
785 - * web.config covers IIS; index.php stops a directory listing on any server.
786 - * nginx honours none of them, so an nginx site still needs a location rule —
787 - * this raises the floor, it does not replace server configuration.
788 - *
789 - * @param string $dir Absolute path to create and protect.
790 - *
791 - * @return bool Whether the directory exists and is usable.
375 + * @param string $process_id The process ID
376 + * @param string $content_id The content ID
377 + * @param string $template The template data (base64 encoded or raw)
378 + * @param array $ai_page_ids Array of AI page IDs
379 + * @param bool $is_preview Whether this is a preview operation
380 + * @param bool $is_skipped Whether the template was skipped
381 + * @return array|WP_Error Result array with status and data
792 382 */
793 - public static function protect_directory( $dir ) {
794 - if ( empty( $dir ) ) {
795 - return false;
383 + public static function save_template_to_file($process_id, $content_id, $template, $ai_page_ids, $is_preview = false, $is_skipped = false) {
384 + $upload_dir = wp_upload_dir();
385 +
386 + // Always save to preview directory for AI content workflow
387 + $tmp_dir = trailingslashit($upload_dir['basedir']) . 'templately' . DIRECTORY_SEPARATOR . 'preview' . DIRECTORY_SEPARATOR . $process_id . DIRECTORY_SEPARATOR;
388 +
389 + // Decode template if it's base64 encoded
390 + if (! empty($template) && base64_decode($template, true) !== false) {
391 + $template = base64_decode($template);
796 392 }
797 393
798 - if ( ! is_dir( $dir ) && ! wp_mkdir_p( $dir ) ) {
799 - return false;
394 + // Handle empty template (skipped)
395 + if (empty($template)) {
396 + $template = json_encode([
397 + "isSkipped" => true,
398 + ]);
800 399 }
801 400
802 - $guards = [
803 - 'index.php' => "<?php\n// Silence is golden.\n",
804 - '.htaccess' => "# Templately working files — not for direct access.\n<IfModule mod_authz_core.c>\n\tRequire all denied\n</IfModule>\n<IfModule !mod_authz_core.c>\n\tOrder allow,deny\n\tDeny from all\n</IfModule>\n",
805 - 'web.config' => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n\t<system.webServer>\n\t\t<authorization>\n\t\t\t<deny users=\"*\" />\n\t\t</authorization>\n\t</system.webServer>\n</configuration>\n",
806 - ];
401 + // Find the correct directory for the content ID
402 + $found_key = null;
403 + foreach ($ai_page_ids as $key => $ids) {
404 + if (in_array($content_id, $ids)) {
405 + $found_key = $key;
406 + break;
407 + }
408 + }
807 409
808 - foreach ( $guards as $file => $contents ) {
809 - $path = trailingslashit( $dir ) . $file;
810 - // Never overwrite: a site owner may have relaxed these deliberately.
811 - if ( ! file_exists( $path ) ) {
812 - @file_put_contents( $path, $contents ); // phpcs:ignore
813 - }
410 + if ($found_key === null) {
411 + return self::error('invalid_content_id', __('Content ID not found in AI page IDs.', 'templately'), 'save_template_to_file', 400);
814 412 }
815 413
816 - return true;
414 + // Create directory and file path
415 + $page_dir = $tmp_dir . $found_key . DIRECTORY_SEPARATOR;
416 + $file_path = $page_dir . $content_id . '.ai.json';
417 + wp_mkdir_p($page_dir);
418 +
419 + // Save the file
420 + $is_success = file_put_contents($file_path, $template);
421 +
422 + if ($is_success) {
423 + // Update processed pages option
424 + $processed_pages = get_option("templately_ai_processed_pages", []);
425 + $processed_pages[$process_id] = $processed_pages[$process_id] ?? [];
426 + $processed_pages[$process_id]['pages'][$content_id] = $is_skipped;
427 + update_option("templately_ai_processed_pages", $processed_pages, false);
428 +
429 + return [
430 + 'status' => 'success',
431 + 'data' => [
432 + 'process_id' => $process_id,
433 + // 'file_path' => $file_path,
434 + 'content_id' => $content_id,
435 + ],
436 + ];
437 + }
438 +
439 + return self::error('file_save_failed', __('Failed to save template file.', 'templately'), 'save_template_to_file', 500);
817 440 }
818 441
819 442 /**
820 - * Absolute path to the plugin's protected working directory in wp-uploads.
443 + * Get matched session data by process ID
821 444 *
822 - * @param string $sub Optional subdirectory ('tmp', 'log', 'preview', ...).
445 + * Helper function to retrieve session data for a given process ID
823 446 *
824 - * @return string Trailing-slashed path, or '' when uploads is unusable.
447 + * @param string $process_id The process ID to match
448 + * @return array|false Returns matched data array or false if not found
825 449 */
826 - public static function upload_dir( $sub = '' ) {
827 - $upload_dir = wp_upload_dir();
450 + public static function get_matched_session_data($process_id) {
451 + if (empty($process_id)) {
452 + return false;
453 + }
828 454
829 - if ( ! empty( $upload_dir['error'] ) || empty( $upload_dir['basedir'] ) ) {
830 - return '';
455 + $all_data = Utils::get_all_session_data();
456 +
457 + if (empty($all_data) || ! is_array($all_data)) {
458 + return false;
831 459 }
832 460
833 - $base = trailingslashit( $upload_dir['basedir'] ) . 'templately' . DIRECTORY_SEPARATOR;
461 + // INSERT_YOUR_CODE
462 + if (is_array($all_data)) {
463 + $all_data = array_reverse($all_data);
464 + }
465 + foreach ($all_data as $data) {
466 + if (isset($data['process_id']) && ($data['process_id'] === $process_id)) {
467 + return $data;
468 + }
469 + }
834 470
835 - // The guards go on the root so every subdirectory inherits them.
836 - self::protect_directory( $base );
837 -
838 - return '' === $sub ? $base : trailingslashit( $base . $sub );
471 + return false;
839 472 }
840 -
841 473 }