PluginProbe
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! / 3.6.0
Templately – Elementor & Gutenberg Template Library: 6500+ Free & Pro Ready Templates And Cloud! v3.6.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 / Utils / Helper.php

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

717 lines 20.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Templately\Utils;
4
5 use Elementor\Plugin;
6 use Templately\Core\Importer\Utils\Utils;
7 use WP_Error;
8 use WP_REST_Response;
9 use function get_plugins;
10 use function is_plugin_active;
11
12 /**
13 * Utility Helper for Templately
14 *
15 * This class contains some helper functions for easy access.
16 *
17 * @since 1.0.0
18 */
19 class Helper extends Base {
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 * Get installed WordPress Plugin List
32 * @return array
33 */
34 public static function get_plugins() {
35 if (! function_exists('get_plugins')) {
36 require_once ABSPATH . 'wp-admin/includes/plugin.php';
37 }
38 return get_plugins();
39 }
40 public static function is_plugins_installed($plugin_file) {
41 $_plugins = self::get_plugins();
42 $is_installed = isset($_plugins[$plugin_file]);
43 return $is_installed;
44 }
45
46 /**
47 * Get installed WordPress Plugin List
48 * @return boolean
49 */
50 public static function is_plugin_active($plugin) {
51 if (! function_exists('is_plugin_active')) {
52 require_once ABSPATH . 'wp-admin/includes/plugin.php';
53 }
54 return is_plugin_active($plugin);
55 }
56
57 /**
58 * Collect IP from request.
59 *
60 * @return string
61 */
62 public static function get_ip() {
63 $ip = '127.0.0.1'; // Local IP
64 if (! empty($_SERVER['HTTP_CLIENT_IP'])) {
65 $ip = $_SERVER['HTTP_CLIENT_IP'];
66 } elseif (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
67 $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
68 } else {
69 $ip = ! empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : $ip;
70 }
71
72 return sanitize_text_field($ip);
73 }
74
75 /**
76 * Get views for front-end display
77 *
78 * @param string $name it will be file name only from the view's folder.
79 * @param array $data
80 * @return void
81 */
82 public static function views($name, $data = []) {
83 extract($data);
84 $helper = self::class;
85 $file = TEMPLATELY_PATH . 'views/' . $name . '.php';
86
87 if (is_readable($file)) {
88 include_once $file;
89 }
90 }
91
92 /**
93 * Get API URL for Templately endpoints
94 *
95 * @param string $endpoint API endpoint path (e.g., 'v2/import/pack/123')
96 * @return string Complete API URL
97 */
98 public static function get_api_url($endpoint): string {
99 $base_url = self::is_dev_api() ? 'https://app.templately.dev' : 'https://app.templately.com';
100
101 /**
102 * Filter the base URL for development API
103 *
104 * @since 3.5.0
105 * @param string $base_url The default base URL
106 */
107 $base_url = apply_filters('templately_dev_api_base_url', $base_url);
108
109 return "{$base_url}/api/{$endpoint}";
110 }
111
112 /**
113 * Make a unified API request to Templately API
114 *
115 * @param string $method HTTP method (GET or POST)
116 * @param string $api_url Complete API URL
117 * @param array $body Request body data (for POST requests)
118 * @param array $extra_headers Additional headers beyond the standard ones
119 * @param int $timeout Request timeout in seconds (default: 30)
120 * @return array|WP_Error Response array or WP_Error on failure
121 */
122 private static function make_api_request($method, $api_url, $body = [], $extra_headers = [], $timeout = 30) {
123 $api_key = Options::get_instance()->get('api_key');
124
125 $headers = [
126 'Authorization' => 'Bearer ' . $api_key,
127 'x-templately-ip' => self::get_ip(),
128 'x-templately-url' => home_url('/'),
129 'x-templately-version' => defined( 'TEMPLATELY_VERSION' ) ? constant( 'TEMPLATELY_VERSION' ) : '1.0.0',
130 ];
131
132 // Add Content-Type for POST requests
133 if (strtoupper($method) === 'POST') {
134 $headers['Content-Type'] = 'application/json';
135 }
136
137 // Merge additional headers
138 $headers = array_merge($headers, $extra_headers);
139
140 $args = [
141 'timeout' => $timeout,
142 'headers' => $headers,
143 ];
144
145 // Apply filter to allow network admin or other functionality to modify request args
146 $args = apply_filters( 'templately_api_request_params', $args, $method, $api_url );
147
148 // Add body for POST requests
149 if (strtoupper($method) === 'POST') {
150 $args['body'] = is_array($body) ? json_encode($body) : $body;
151 }
152
153 // Make the appropriate request
154 if (strtoupper($method) === 'POST') {
155 $response = wp_remote_post($api_url, $args);
156 } else {
157 $response = wp_remote_get($api_url, $args);
158 }
159
160 // Check for verification header in the response
161 self::check_verification_header($response);
162
163
164 // Check for site disconnection in response body
165 self::check_site_disconnection($response);
166
167 return $response;
168 }
169
170 /**
171 * Make a GET request to Templately API
172 *
173 * @param string $endpoint API endpoint path (e.g., 'v2/import/pack/123')
174 * @param array $query_params Query parameters as key-value pairs
175 * @param array $extra_headers Additional headers beyond the standard ones
176 * @param int $timeout Request timeout in seconds (default: 30)
177 * @return array|WP_Error Response array or WP_Error on failure
178 */
179 public static function make_api_get_request($endpoint, $query_params = [], $extra_headers = [], $timeout = 30) {
180 $api_url = self::get_api_url($endpoint);
181
182 // Add query parameters if provided
183 if (!empty($query_params)) {
184 $api_url = add_query_arg($query_params, $api_url);
185 }
186
187 return self::make_api_request('GET', $api_url, [], $extra_headers, $timeout);
188 }
189
190 /**
191 * Make a POST request to Templately API
192 *
193 * @param string $endpoint API endpoint path (e.g., 'v2/feedback/store')
194 * @param array $body Request body data
195 * @param array $extra_headers Additional headers beyond the standard ones
196 * @param int $timeout Request timeout in seconds (default: 30)
197 * @return array|WP_Error Response array or WP_Error on failure
198 */
199 public static function make_api_post_request($endpoint, $body = [], $extra_headers = [], $timeout = 30) {
200 $api_url = self::get_api_url($endpoint);
201 return self::make_api_request('POST', $api_url, $body, $extra_headers, $timeout);
202 }
203
204 /**
205 * Sanitize Helper
206 *
207 * @param mixed $value
208 * @param string $type
209 *
210 * @return bool|string
211 */
212 public static function sanitize($value, $type = 'text') {
213 switch ($type) {
214 case 'boolean':
215 $sanitized_value = rest_sanitize_boolean($value);
216 break;
217 default:
218 $sanitized_value = sanitize_text_field($value);
219 break;
220 }
221
222 return $sanitized_value;
223 }
224
225 /**
226 * Escape a string for safe embedding inside a GraphQL or JSON string literal.
227 *
228 * GraphQL string escaping rules are identical to JSON string escaping (per the
229 * GraphQL spec), so wp_json_encode() is the authoritative escaper. We strip the
230 * outer quotes it adds and return only the escaped inner content, ready to be
231 * wrapped in your own quote pair.
232 *
233 * Handles pre-encoded JSON: when the caller has already run json_encode() +
234 * wp_slash() on a value (e.g. categories, dependencies in Items.php), the
235 * quotes are already escaped as \" and the string is ready to embed. Calling
236 * wp_json_encode() again would double-escape those backslashes. We detect this
237 * case by checking whether wp_unslash() produces valid JSON, and if so, return
238 * the value directly without further encoding.
239 *
240 * @param string $value Raw string or wp_slash(json_encode()) output.
241 * @return string Escaped string, safe to place between double quotes in GraphQL/JSON.
242 */
243 public static function esc_json_string( $value ) {
244 $value = (string) $value;
245
246 // If wp_slash() was applied to a JSON string upstream, the quotes are
247 // already escaped (e.g. {\"key\":\"val\"}). Detect this by unslashing and
248 // checking for valid JSON — if it matches, the value is already suitable
249 // for embedding in a string literal; return it as-is to avoid doubling backslashes.
250 $unslashed = wp_unslash( $value );
251 if ( $unslashed !== $value ) {
252 $decoded = json_decode( $unslashed, true );
253 if ( json_last_error() === JSON_ERROR_NONE && null !== $decoded ) {
254 return $value;
255 }
256 }
257
258 $encoded = wp_json_encode( $value );
259 // wp_json_encode wraps the value in "...", strip those outer quotes.
260 return substr( $encoded, 1, -1 );
261 }
262
263 /**
264 * Check for X-Templately-Verified header and update user verification status
265 *
266 * @param array|WP_Error $response The HTTP response array from wp_remote_get/wp_remote_post
267 * @return void
268 */
269 public static function check_verification_header($response) {
270 // Only process if response is not a WP_Error and contains headers
271 if (is_wp_error($response)) {
272 return;
273 }
274
275 // Retrieve the X-Templately-Verified header
276 $verification_header = wp_remote_retrieve_header($response, 'X-Templately-Verified');
277
278 // Check if header exists and has a truthy value
279 if (!empty($verification_header) && filter_var($verification_header, FILTER_VALIDATE_BOOLEAN)) {
280 try {
281 // Get current user data
282 $options = Options::get_instance();
283 $user = $options->get('user');
284
285 // Only update if user data exists and is not already verified
286 if (!empty($user) && is_array($user) && empty($user['is_verified'])) {
287 // Set verification flag
288 $user['is_verified'] = true;
289
290 // Save updated user data
291 $options->set('user', $user);
292
293 }
294
295 if (!empty($user['is_verified'])){
296 if(!headers_sent()){
297 header( 'X-Templately-Verified: true' );
298 if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
299 self::log('User verification status already updated via X-Templately-Verified header');
300 }
301 }
302
303 return true;
304 }
305 } catch (\Exception $e) {
306 // Log error if debug logging is enabled
307 if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
308 self::log('Error updating user verification status: ' . $e->getMessage());
309 }
310 }
311 }
312
313 return false;
314 }
315
316 /**
317 * Check for site disconnection status in API response body
318 *
319 * Detects SiteNotConnected errors and updates user disconnection status.
320 * Sends X-Templately-Disconnected header for frontend detection.
321 *
322 *
323 * @param array|WP_Error|mixed $response The response object or body array
324 * @return bool True if site is disconnected, false otherwise
325 */
326 public static function check_site_disconnection($response) {
327 if (is_wp_error($response)) {
328 return false;
329 }
330
331 $response_body = $response;
332
333 // If it's a raw WP response array with body, decode it
334 if (is_array($response) && isset($response['body']) && is_string($response['body'])) {
335 $response_body = json_decode(wp_remote_retrieve_body($response), true);
336 }
337
338 // Check if response body indicates site disconnection
339 if (!is_array($response_body)) {
340 return false;
341 }
342
343 $status = $response_body['status'] ?? null;
344 $status_text = $response_body['statusText'] ?? null;
345
346 // Check for SiteNotConnected error
347 if ($status === 'error' && $status_text === 'SiteNotConnected') {
348 try {
349 // Get current user data
350 $options = Options::get_instance();
351 $user = $options->get('user');
352
353 // Only update if user data exists
354 if (!empty($user) && is_array($user)) {
355 // Set disconnection flag
356 $user['is_disconnected'] = true;
357
358 // Save updated user data
359 $options->set('user', $user);
360
361 if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
362 self::log('Site disconnection detected: SiteNotConnected status');
363 }
364 }
365
366 // Send header for frontend detection
367 if (!headers_sent()) {
368 header('X-Templately-Disconnected: true');
369 }
370
371 return true;
372 } catch (\Exception $e) {
373 // Log error if debug logging is enabled
374 if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
375 self::log('Error updating site disconnection status: ' . $e->getMessage());
376 }
377 }
378 }
379
380 return false;
381 }
382
383 /**
384 * Clear site disconnection status
385 *
386 * Called after successful site migration to reset the disconnection flag.
387 *
388 * @return void
389 */
390 public static function clear_site_disconnection() {
391 try {
392 $options = Options::get_instance();
393 $user = $options->get('user');
394
395 if (!empty($user) && is_array($user)) {
396 $user['site_url'] = base64_encode( home_url('/') );
397 $user['is_disconnected'] = false;
398 $options->set('user', $user);
399
400 if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
401 self::log('Site disconnection status cleared and URL updated.');
402 }
403 }
404 } catch (\Exception $e) {
405 if (defined('TEMPLATELY_DEBUG_LOG') && constant('TEMPLATELY_DEBUG_LOG')) {
406 self::log('Error clearing site disconnection status: ' . $e->getMessage());
407 }
408 }
409 }
410
411 /**
412 * API Error Formatter
413 *
414 * @param int $error_code
415 * @param mixed $error_message
416 * @param string $endpoint
417 * @param integer $status
418 * @param array $additional_data
419 * @return WP_Error
420 */
421 public static function error($error_code, $error_message, $endpoint = '', $status = 500, $additional_data = []) {
422 $additional_data['status'] = $status;
423 if (! empty($endpoint)) {
424 $additional_data['endpoint'] = $endpoint;
425 }
426 // Add browser padding to avoid browsers not serving small JSON responses
427 $padding_length = 512;
428 $additional_data['browser_padding'] = str_repeat(' ', $padding_length);
429
430 return new WP_Error($error_code, $error_message, $additional_data);
431 }
432
433 /**
434 * API Response Formatter
435 *
436 * @param mixed $data
437 * @return WP_REST_Response
438 */
439 public static function success($data) {
440 return new WP_REST_Response($data, 200);
441 }
442
443 /**
444 * Normalize Favourites Data
445 *
446 * @param array $favourites
447 * @param array $_favourites
448 * @param boolean $undo
449 *
450 * @return array
451 */
452 public function normalizeFavourites($favourites, $_favourites = [], $undo = false) {
453 if ($undo) {
454 $_favourites[$favourites['type']] = array_values(array_filter($_favourites[$favourites['type']], function ($item) use ($favourites) {
455 return $item != $favourites['id'];
456 }));
457 return $_favourites;
458 }
459
460 array_map(function ($item) use (&$_favourites) {
461 if (! is_null($item)) {
462 $item = (array) $item;
463 if (isset($_favourites[$item['type']])) {
464 $_favourites[$item['type']][] = $item['id'];
465 } else {
466 $_favourites[$item['type']] = [$item['id']];
467 }
468 }
469 return $_favourites;
470 }, $favourites);
471
472 return $_favourites;
473 }
474
475 public function normalizeReviews($favourites, $_favourites = [], $undo = false) {
476 array_map(function ($item) use (&$_favourites) {
477 if (! is_null($item)) {
478 $item = (array) $item;
479 if (!isset($_favourites[$item['type']])) {
480 $_favourites[$item['type']] = [];
481 }
482 $_favourites[$item['type']][$item['type_id']] = $item['rating'];
483 }
484 return $_favourites;
485 }, $favourites);
486
487 return $_favourites;
488 }
489
490 /**
491 * Trigger Error
492 *
493 * @param object $triggered_by
494 * @return void
495 */
496 public static function trigger_error($triggered_by, $method = 'get_instance') {
497 $class = get_class($triggered_by);
498 $trace = debug_backtrace(); // phpcs:ignore PHPCompatibility.FunctionUse.ArgumentFunctionsReportCurrentValue.NeedsInspection
499 $file = $trace[0]['file'];
500 $line = $trace[0]['line'];
501 trigger_error("Call to undefined method $class::$method() in $file on line $line", E_USER_ERROR);
502 }
503
504 /**
505 * Printing Error Logs in debug.log file.
506 *
507 * @param mixed $log The data to log
508 * @param string $context Optional context for categorizing log entries
509 * @param string $level Optional log level (debug, info, warning, error)
510 * @return void
511 */
512 public static function log($log, $context = '', $level = 'info') {
513 // Allow complete override of logging behavior
514 $override_result = apply_filters('templately_log_override', null, $log, $context, $level);
515 if ($override_result !== null) {
516 return;
517 }
518
519 // Only log if WP_DEBUG_LOG is enabled
520 if (!defined('WP_DEBUG_LOG') || !WP_DEBUG_LOG) {
521 return;
522 }
523
524 // Format the log message
525 $formatted_message = self::format_log_message($log, $context, $level);
526
527 // Write to error log
528 error_log($formatted_message);
529 }
530
531 /**
532 * Format log message with context and level
533 *
534 * @param mixed $log The data to log
535 * @param string $context Context for categorizing log entries
536 * @param string $level Log level
537 * @return string Formatted log message
538 */
539 private static function format_log_message($log, $context = '', $level = 'info') {
540 // Convert arrays and objects to readable format
541 if (is_array($log) || is_object($log)) {
542 $log_content = print_r($log, true);
543 } else {
544 $log_content = (string) ($log ?: '');
545 }
546
547 // Build the formatted message
548 $timestamp = current_time('Y-m-d H:i:s');
549 $level_upper = strtoupper($level);
550
551 if (!empty($context)) {
552 return "[{$timestamp}] [{$level_upper}] [{$context}] {$log_content}";
553 } else {
554 return "[{$timestamp}] [{$level_upper}] {$log_content}";
555 }
556 }
557
558 public static function should_flush() {
559 if (isset($_REQUEST['is_lightspeed']) && $_REQUEST['is_lightspeed'] === 'true') {
560 return false;
561 }
562 return (!defined('TEMPLATELY_IGNORE_FLUSH_ALL') || !TEMPLATELY_IGNORE_FLUSH_ALL) && strpos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') === false;
563 }
564
565 public static function get_block_by_name($blocks, $search) {
566 $queue = $blocks;
567
568 while (!empty($queue)) {
569 $current_block = array_shift($queue);
570
571 if ($search === $current_block['blockName']) {
572 return $current_block;
573 }
574
575 if (isset($current_block['innerBlocks'])) {
576 // Add nested blocks to the end of the queue for processing
577 $queue = array_merge($queue, $current_block['innerBlocks']);
578 }
579 }
580
581 return false;
582 }
583
584 /**
585 * Only checks if user can install/activate plugins
586 *
587 * @param [type] $cap
588 * @param [type] ...$args
589 * @return void
590 */
591 public static function current_user_can($cap, ...$args) {
592 $user = wp_get_current_user();
593
594 // Multisite super admin has all caps by definition, Unless specifically denied.
595 if (is_multisite() && is_super_admin($user->ID)) {
596 return true;
597 }
598
599 $caps = map_meta_cap($cap, $user->ID, ...$args);
600
601 switch ($cap) {
602 case 'install_plugins':
603 case 'upload_plugins':
604 $caps = ['install_plugins'];
605 break;
606 case 'install_themes':
607 case 'upload_themes':
608 $caps = ['install_themes'];
609 break;
610 case 'activate_plugins':
611 case 'deactivate_plugins':
612 case 'activate_plugin':
613 case 'deactivate_plugin':
614 $caps = ['activate_plugins'];
615 break;
616 default:
617 break;
618 }
619
620 // Maintain BC for the argument passed to the "user_has_cap" filter.
621 $args = array_merge(array($cap, $user->ID), $args);
622
623 /**
624 * See WP_User::has_cap() for description.
625 */
626 $capabilities = apply_filters('user_has_cap', $user->allcaps, $caps, $args, $user);
627
628 // Everyone is allowed to exist.
629 $capabilities['exist'] = true;
630
631 // Nobody is allowed to do things they are not allowed to do.
632 unset($capabilities['do_not_allow']);
633
634 // Must have ALL requested caps.
635 foreach ((array) $caps as $cap) {
636 if (empty($capabilities[$cap])) {
637 return false;
638 }
639 }
640
641 return true;
642 }
643
644 /**
645 * Calculates the elapsed time and checks if it is close to the maximum execution time.
646 * Returns true if the script should exit to avoid exceeding the limit.
647 *
648 * @return bool True if the script should exit, false otherwise.
649 */
650 public static function fsi_should_exit() {
651 if (defined('TEMPLATELY_START_TIME') && ini_get('max_execution_time')) {
652 $max_time = ini_get('max_execution_time');
653 $elapsed = microtime(true) - TEMPLATELY_START_TIME;
654 $delay = max(5, $max_time * 20 / 100);
655
656 // Check if elapsed time is close to max execution time
657 if ($max_time - $elapsed <= $delay) {
658 return ['max_time' => $max_time, 'elapsed' => $elapsed, 'delay' => $delay];
659 }
660 }
661 return false;
662 }
663
664 /**
665 * Enable Elementor Container
666 * This function will enable the Elementor Container feature.
667 * Without this feature, some of the templates may not work properly.
668 *
669 * @return boolean
670 */
671 public static function enable_elementor_container() {
672 if (class_exists('Elementor\Plugin')) {
673 $control_name = Plugin::instance()->experiments->get_feature_option_key('container');
674 if (get_option($control_name) !== 'active') {
675 update_option($control_name, 'active');
676 return true;
677 }
678 }
679 return false;
680 }
681
682 /**
683 * Undocumented function
684 *
685 * @param [type] $args
686 * @param [type] $defaults
687 * @return array
688 */
689 public static function recursive_wp_parse_args($args, $defaults) {
690 $args = (array) $args;
691 $defaults = (array) $defaults;
692 $r = $defaults;
693 foreach ($args as $key => $value) {
694 if (is_array($value) && isset($r[$key])) {
695 // also handle numeric array. if both $value and $r[ $key ] are numeric array. wp_is_numeric_array()
696 if (wp_is_numeric_array($value) && wp_is_numeric_array($r[$key])) {
697 foreach ($value as $k => $v) {
698 if (!in_array($v, $r[$key])) {
699 if (!isset($r[$key][$k])) {
700 $r[$key][$k] = $v;
701 } else {
702 $r[$key][] = $v;
703 }
704 }
705 }
706 } else {
707 $r[$key] = self::recursive_wp_parse_args($value, $r[$key]);
708 }
709 } else {
710 $r[$key] = $value;
711 }
712 }
713 return $r;
714 }
715
716 }
717