PluginProbe
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz / 1.0.5
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz v1.0.5
2.12.6 2.12.5 2.12.4 2.12.3 2.12.2 2.12.1 2.12.0 2.11.1 2.11.0 2.10.1 2.10.0 2.9.1 2.9.0 2.8.2 2.8.1 2.7.0 2.7.1 2.8.0 trunk 0.0.10 0.0.11 0.0.12 0.0.13 0.0.2 0.0.3 All 96 releases
sureforms / inc / helper.php

helper.php in SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz 1.0.5, at inc/helper.php

975 lines 33.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Sureforms Submit Class file.
4 *
5 * @package sureforms.
6 * @since 0.0.1
7 */
8
9 namespace SRFM\Inc;
10
11 use SRFM\Inc\Database\Tables\Entries;
12 use SRFM\Inc\Traits\Get_Instance;
13 use WP_Error;
14 use WP_Post;
15 use WP_Post_Type;
16
17 if ( ! defined( 'ABSPATH' ) ) {
18 exit; // Exit if accessed directly.
19 }
20
21 /**
22 * Sureforms Helper Class.
23 *
24 * @since 0.0.1
25 */
26 class Helper {
27 use Get_Instance;
28
29 /**
30 * Sureforms SVGs.
31 *
32 * @var mixed srfm_svgs
33 */
34 private static $srfm_svgs = null;
35
36 /**
37 * Get common error message.
38 *
39 * @since 0.0.2
40 * @return array<string>
41 */
42 public static function get_common_err_msg() {
43 return [
44 'required' => __( 'This field is required.', 'sureforms' ),
45 'unique' => __( 'Value needs to be unique.', 'sureforms' ),
46 ];
47 }
48
49 /**
50 * Checks if current value is string or else returns default value
51 *
52 * @param mixed $data data which need to be checked if is string.
53 *
54 * @since 0.0.1
55 * @return string
56 */
57 public static function get_string_value( $data ) {
58 if ( is_scalar( $data ) ) {
59 return (string) $data;
60 }
61 if ( is_object( $data ) && method_exists( $data, '__toString' ) ) {
62 return $data->__toString();
63 }
64 if ( is_null( $data ) ) {
65 return '';
66 }
67 return '';
68 }
69 /**
70 * Checks if current value is number or else returns default value
71 *
72 * @param mixed $value data which need to be checked if is string.
73 * @param int $base value can be set is $data is not a string, defaults to empty string.
74 *
75 * @since 0.0.1
76 * @return int
77 */
78 public static function get_integer_value( $value, $base = 10 ) {
79 if ( is_numeric( $value ) ) {
80 return (int) $value;
81 }
82 if ( is_string( $value ) ) {
83 $trimmed_value = trim( $value );
84 return intval( $trimmed_value, $base );
85 }
86 return 0;
87 }
88
89 /**
90 * Checks if current value is an array or else returns default value
91 *
92 * @param mixed $data Data which needs to be checked if it is an array.
93 *
94 * @since 0.0.3
95 * @return array<mixed>
96 */
97 public static function get_array_value( $data ) {
98 if ( is_array( $data ) ) {
99 return $data;
100 }
101 if ( is_null( $data ) ) {
102 return [];
103 }
104 return (array) $data;
105 }
106
107 /**
108 * Extracts the field type from the dynamic field key ( or field slug ).
109 *
110 * @param string $field_key Dynamic field key.
111 * @since 0.0.6
112 * @return string Extracted field type.
113 */
114 public static function get_field_type_from_key( $field_key ) {
115
116 if ( false === strpos( $field_key, '-lbl-' ) ) {
117 return '';
118 }
119
120 return trim( explode( '-', $field_key )[1] );
121 }
122
123 /**
124 * Returns the proper sanitize callback functions according to the field type.
125 *
126 * @param string $field_type HTML field type.
127 * @since 0.0.6
128 * @return callable Returns sanitize callbacks according to the provided field type.
129 */
130 public static function get_field_type_sanitize_function( $field_type ) {
131 $callbacks = apply_filters(
132 'srfm_field_type_sanitize_functions',
133 [
134 'url' => 'esc_url_raw',
135 'input' => 'sanitize_text_field',
136 'number' => [ self::class, 'sanitize_number' ],
137 'email' => 'sanitize_email',
138 'textarea' => 'sanitize_textarea_field',
139 ]
140 );
141
142 return $callbacks[ $field_type ] ?? 'sanitize_text_field';
143 }
144
145 /**
146 * Sanitizes a numeric value.
147 *
148 * This function checks if the input value is numeric. If it is numeric, it sanitizes
149 * the value to ensure it's a float or integer, allowing for fractions and thousand separators.
150 * If the value is not numeric, it sanitizes it as a text field.
151 *
152 * @param mixed $value The value to be sanitized.
153 * @since 0.0.6
154 * @return int|float|string The sanitized value.
155 */
156 public static function sanitize_number( $value ) {
157 if ( ! is_numeric( $value ) ) {
158 // phpcs:ignore /** @phpstan-ignore-next-line */
159 return sanitize_text_field( $value ); // If it is not numeric, then let user get some sanitized data to view.
160 }
161
162 // phpcs:ignore /** @phpstan-ignore-next-line */
163 return sanitize_text_field( filter_var( $value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND ) );
164 }
165
166 /**
167 * This function sanitizes the submitted form data according to the field type.
168 *
169 * @param array<mixed> $form_data $form_data User submitted form data.
170 * @since 0.0.6
171 * @return array<mixed> $result Sanitized form data.
172 */
173 public static function sanitize_by_field_type( $form_data ) {
174 $result = [];
175
176 if ( empty( $form_data ) || ! is_array( $form_data ) ) {
177 return $result;
178 }
179
180 foreach ( $form_data as $field_key => &$value ) {
181 $field_type = self::get_field_type_from_key( $field_key );
182 $sanitize_function = self::get_field_type_sanitize_function( $field_type );
183 $sanitized_data = is_array( $value ) ? self::sanitize_by_field_type( $value ) : call_user_func( $sanitize_function, $value );
184
185 $result[ $field_key ] = $sanitized_data;
186 }
187
188 return $result;
189 }
190
191 /**
192 * This function performs array_map for multi dimensional array
193 *
194 * @param string $function function name to be applied on each element on array.
195 * @param array<mixed> $data_array array on which function needs to be performed.
196 * @return array<mixed>
197 * @since 0.0.1
198 */
199 public static function sanitize_recursively( $function, $data_array ) {
200 $response = [];
201 if ( is_array( $data_array ) ) {
202 if ( ! is_callable( $function ) ) {
203 return $data_array;
204 }
205 foreach ( $data_array as $key => $data ) {
206 $val = is_array( $data ) ? self::sanitize_recursively( $function, $data ) : $function( $data );
207 $response[ $key ] = $val;
208 }
209 }
210
211 return $response;
212 }
213
214 /**
215 * Generates common markup liked label, etc
216 *
217 * @param int|string $form_id form id.
218 * @param string $type Type of form markup.
219 * @param string $label Label for the form markup.
220 * @param string $slug Slug for the form markup.
221 * @param string $block_id Block id for the form markup.
222 * @param bool $required If field is required or not.
223 * @param string $help Help for the form markup.
224 * @param string $error_msg Error message for the form markup.
225 * @param bool $is_unique Check if the field is unique.
226 * @param string $duplicate_msg Duplicate message for field.
227 * @param bool $override Override for error markup.
228 * @return string
229 * @since 0.0.1
230 */
231 public static function generate_common_form_markup( $form_id, $type, $label = '', $slug = '', $block_id = '', $required = false, $help = '', $error_msg = '', $is_unique = false, $duplicate_msg = '', $override = false ) {
232 $duplicate_msg = $duplicate_msg ? ' data-unique-msg="' . esc_attr( $duplicate_msg ) . '"' : '';
233
234 $markup = '';
235 $show_labels_as_placeholder = get_post_meta( self::get_integer_value( $form_id ), '_srfm_use_label_as_placeholder', true );
236 $show_labels_as_placeholder = $show_labels_as_placeholder ? self::get_string_value( $show_labels_as_placeholder ) : false;
237
238 switch ( $type ) {
239 case 'label':
240 $markup = $label ? '<label for="srfm-' . $slug . '-' . esc_attr( $block_id ) . '" class="srfm-block-label">' . htmlspecialchars_decode( esc_html( $label ) ) . ( $required ? '<span class="srfm-required" aria-label="' . esc_attr__( 'Required', 'sureforms' ) . '"><span aria-hidden="true"> *</span></span>' : '' ) . '</label>' : '';
241 break;
242 case 'help':
243 $markup = $help ? '<div class="srfm-description" id="srfm-description-' . esc_attr( $block_id ) . '">' . wp_kses_post( htmlspecialchars_decode( $help ) ) . '</div>' : '';
244 break;
245 case 'error':
246 $markup = $required || $override ? '<div class="srfm-error-message" id="srfm-error-' . esc_attr( $block_id ) . '" data-error-msg="' . esc_attr( $error_msg ) . '"' . $duplicate_msg . '>' . esc_html( $error_msg ) . '</div>' : '';
247 break;
248 case 'is_unique':
249 $markup = $is_unique ? '<div class="srfm-error">' . esc_html( $duplicate_msg ) . '</div>' : '';
250 break;
251 case 'placeholder':
252 $markup = $label && '1' === $show_labels_as_placeholder ? $label . ( $required ? ' *' : '' ) : '';
253 break;
254 default:
255 $markup = '';
256 }
257
258 return $markup;
259 }
260
261 /**
262 * Get an SVG Icon
263 *
264 * @since 0.0.1
265 * @param string $icon the icon name.
266 * @param string $class if the baseline class should be added.
267 * @param string $html Custom attributes inside svg wrapper.
268 * @return string
269 */
270 public static function fetch_svg( $icon = '', $class = '', $html = '' ) {
271 $class = $class ? ' ' . $class : '';
272
273 $output = '<span class="srfm-icon' . $class . '" ' . $html . '>';
274 if ( ! self::$srfm_svgs ) {
275 ob_start();
276
277 include_once SRFM_DIR . 'assets/svg/svgs.json';
278 self::$srfm_svgs = json_decode( self::get_string_value( ob_get_clean() ), true );
279 self::$srfm_svgs = apply_filters( 'srfm_svg_icons', self::$srfm_svgs );
280 }
281
282 $output .= self::$srfm_svgs[ $icon ] ?? '';
283 $output .= '</span>';
284
285 return $output;
286 }
287
288 /**
289 * Encrypt data using base64.
290 *
291 * @param string $input The input string which needs to be encrypted.
292 * @since 0.0.1
293 * @return string The encrypted string.
294 */
295 public static function encrypt( $input ) {
296 // If the input is empty or not a string, then abandon ship.
297 if ( empty( $input ) || ! is_string( $input ) ) {
298 return '';
299 }
300
301 // Encrypt the input and return it.
302 $base_64 = base64_encode( $input ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
303 return rtrim( $base_64, '=' );
304 }
305
306 /**
307 * Decrypt data using base64.
308 *
309 * @param string $input The input string which needs to be decrypted.
310 * @since 0.0.1
311 * @return string The decrypted string.
312 */
313 public static function decrypt( $input ) {
314 // If the input is empty or not a string, then abandon ship.
315 if ( empty( $input ) || ! is_string( $input ) ) {
316 return '';
317 }
318
319 // Decrypt the input and return it.
320 $base_64 = $input . str_repeat( '=', strlen( $input ) % 4 );
321 return base64_decode( $base_64 ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
322 }
323
324 /**
325 * Update an option from the database.
326 *
327 * @param string $key The option key.
328 * @param mixed $value The value to update.
329 * @param bool $network_override Whether to allow the network_override admin setting to be overridden on subsites.
330 * @since 0.0.1
331 * @return bool True if the option was updated, false otherwise.
332 */
333 public static function update_admin_settings_option( $key, $value, $network_override = false ) {
334 // Update the site-wide option if we're in the network admin, and return the updated status.
335 return $network_override && is_multisite() ? update_site_option( $key, $value ) : update_option( $key, $value );
336 }
337
338 /**
339 * Update an option from the database.
340 *
341 * @param int|string $post_id post id / form id.
342 * @param string $key meta key name.
343 * @param bool $single single or multiple.
344 * @param mixed $default default value.
345 *
346 * @since 0.0.1
347 * @return string Meta value.
348 */
349 public static function get_meta_value( $post_id, $key, $single = true, $default = '' ) {
350 $srfm_live_mode_data = self::get_instant_form_live_data();
351
352 if ( isset( $srfm_live_mode_data[ $key ] ) ) {
353 // Give priority to live mode data if we have one set from the Instant Form.
354 return self::get_string_value( $srfm_live_mode_data[ $key ] );
355 }
356
357 return get_post_meta( self::get_integer_value( $post_id ), $key, $single ) ? self::get_string_value( get_post_meta( self::get_integer_value( $post_id ), $key, $single ) ) : self::get_string_value( $default );
358 }
359
360 /**
361 * Wrapper for the WordPress's get_post_meta function with the support for default values.
362 *
363 * @param int|string $post_id Post ID.
364 * @param string $key The meta key to retrieve.
365 * @param mixed $default Default value.
366 * @param bool $single Optional. Whether to return a single value.
367 * @since 0.0.8
368 * @return mixed Meta value.
369 */
370 public static function get_post_meta( $post_id, $key, $default = null, $single = true ) {
371 $meta_value = get_post_meta( self::get_integer_value( $post_id ), $key, $single );
372 return $meta_value ? $meta_value : $default;
373 }
374
375 /**
376 * Returns query params data for instant form live preview.
377 *
378 * @since 0.0.8
379 * @return array<mixed> Live preview data.
380 */
381 public static function get_instant_form_live_data() {
382 $srfm_live_mode_data = isset( $_GET['live_mode'] ) && current_user_can( 'edit_posts' ) ? self::sanitize_recursively( 'sanitize_text_field', wp_unslash( $_GET ) ) : []; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
383
384 return $srfm_live_mode_data ? array_map(
385 // Normalize falsy values.
386 static function( $live_data ) {
387 return 'false' === $live_data ? false : $live_data;
388 },
389 $srfm_live_mode_data
390 ) : [];
391 }
392
393 /**
394 * Default dynamic block value.
395 *
396 * @since 0.0.1
397 * @return array<string> Meta value.
398 */
399 public static function default_dynamic_block_option() {
400
401 $common_err_msg = self::get_common_err_msg();
402
403 $default_values = [
404 'srfm_url_block_required_text' => $common_err_msg['required'],
405 'srfm_input_block_required_text' => $common_err_msg['required'],
406 'srfm_input_block_unique_text' => $common_err_msg['unique'],
407 'srfm_address_block_required_text' => $common_err_msg['required'],
408 'srfm_phone_block_required_text' => $common_err_msg['required'],
409 'srfm_phone_block_unique_text' => $common_err_msg['unique'],
410 'srfm_number_block_required_text' => $common_err_msg['required'],
411 'srfm_textarea_block_required_text' => $common_err_msg['required'],
412 'srfm_multi_choice_block_required_text' => $common_err_msg['required'],
413 'srfm_checkbox_block_required_text' => $common_err_msg['required'],
414 'srfm_gdpr_block_required_text' => $common_err_msg['required'],
415 'srfm_email_block_required_text' => $common_err_msg['required'],
416 'srfm_email_block_unique_text' => $common_err_msg['unique'],
417 'srfm_dropdown_block_required_text' => $common_err_msg['required'],
418 'srfm_rating_block_required_text' => $common_err_msg['required'],
419 ];
420
421 return apply_filters( 'srfm_default_dynamic_block_option', $default_values, $common_err_msg );
422 }
423
424 /**
425 * Get default dynamic block value.
426 *
427 * @param string $key meta key name.
428 * @since 0.0.1
429 * @return string Meta value.
430 */
431 public static function get_default_dynamic_block_option( $key ) {
432 $default_dynamic_values = self::default_dynamic_block_option();
433 $option = get_option( 'srfm_default_dynamic_block_option', $default_dynamic_values );
434
435 if ( is_array( $option ) && array_key_exists( $key, $option ) ) {
436 return $option[ $key ];
437 }
438 return '';
439 }
440
441 /**
442 * Checks whether a given request has appropriate permissions.
443 *
444 * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
445 * @since 0.0.1
446 */
447 public static function get_items_permissions_check() {
448 if ( current_user_can( 'edit_posts' ) ) {
449 return true;
450 }
451
452 foreach ( get_post_types( [ 'show_in_rest' => true ], 'objects' ) as $post_type ) {
453 /**
454 * The post type.
455 *
456 * @var WP_Post_Type $post_type
457 */
458 if ( current_user_can( $post_type->cap->edit_posts ) ) {
459 return true;
460 }
461 }
462
463 return new WP_Error(
464 'rest_cannot_view',
465 __( 'Sorry, you are not allowed to perform this action.', 'sureforms' ),
466 [ 'status' => \rest_authorization_required_code() ]
467 );
468 }
469
470 /**
471 * Check if the current user has a given capability.
472 *
473 * @param string $capability The capability to check.
474 * @since 0.0.3
475 * @return bool Whether the current user has the given capability or role.
476 */
477 public static function current_user_can( $capability = '' ) {
478
479 if ( ! function_exists( 'current_user_can' ) ) {
480 return false;
481 }
482
483 if ( ! is_string( $capability ) || empty( $capability ) ) {
484 $capability = 'edit_posts';
485 }
486
487 return current_user_can( $capability );
488 }
489
490 /**
491 * Get all the entries for the given form ids. The entries are older than the given days_old.
492 *
493 * @param int $days_old The number of days old the entries should be.
494 * @param array<int> $sf_form_ids The form ids for which the entries need to be fetched.
495 * @since 0.0.2
496 * @return array<mixed> the entries matching the criteria.
497 */
498 public static function get_entries_from_form_ids( $days_old = 0, $sf_form_ids = [] ) {
499
500 $entries = [];
501 $days_old_date = ( new \DateTime() )->modify( "-{$days_old} days" )->format( 'Y-m-d H:i:s' );
502
503 foreach ( $sf_form_ids as $form_id ) {
504 // args according to the get_all() function in the Entries class.
505 $args = [
506 'where' => [
507 [
508 [
509 'key' => 'form_id',
510 'value' => $form_id,
511 'compare' => '=',
512 ],
513 [
514 'key' => 'created_at',
515 'value' => $days_old_date,
516 'compare' => '<=',
517 ],
518 ],
519 ],
520 ];
521
522 // store all the entries in a single array.
523 $entries = array_merge( $entries, Entries::get_all( $args, false ) );
524 }
525 return $entries;
526 }
527
528 /**
529 * Decode block attributes.
530 * The function reverses the effect of serialize_block_attributes()
531 *
532 * @link https://developer.wordpress.org/reference/functions/serialize_block_attributes/
533 * @param string $encoded_data the encoded block attribute.
534 * @since 0.0.2
535 * @return string decoded block attribute
536 */
537 public static function decode_block_attribute( $encoded_data = '' ) {
538 $decoded_data = preg_replace( '/\\\\u002d\\\\u002d/', '--', self::get_string_value( $encoded_data ) );
539 $decoded_data = preg_replace( '/\\\\u003c/', '<', self::get_string_value( $decoded_data ) );
540 $decoded_data = preg_replace( '/\\\\u003e/', '>', self::get_string_value( $decoded_data ) );
541 $decoded_data = preg_replace( '/\\\\u0026/', '&', self::get_string_value( $decoded_data ) );
542 $decoded_data = preg_replace( '/\\\\\\\\"/', '"', self::get_string_value( $decoded_data ) );
543 return self::get_string_value( $decoded_data );
544 }
545
546 /**
547 * Map slugs to submission data.
548 *
549 * @param array<mixed> $submission_data submission_data.
550 * @since 0.0.3
551 * @return array<mixed>
552 */
553 public static function map_slug_to_submission_data( $submission_data = [] ) {
554 $mapped_data = [];
555 foreach ( $submission_data as $key => $value ) {
556 if ( false === strpos( $key, '-lbl-' ) ) {
557 continue;
558 }
559 $label = explode( '-lbl-', $key )[1];
560 $slug = implode( '-', array_slice( explode( '-', $label ), 1 ) );
561 $mapped_data[ $slug ] = $value;
562 }
563 return $mapped_data;
564 }
565
566 /**
567 * Get forms options. Shows all the available forms in the dropdown.
568 *
569 * @since 0.0.5
570 * @param string $key Determines the type of data to return.
571 * @return array<mixed>
572 */
573 public static function get_sureforms( $key = '' ) {
574 $forms = get_posts(
575 apply_filters(
576 'srfm_get_sureforms_query_args',
577 [
578 'post_type' => SRFM_FORMS_POST_TYPE,
579 'posts_per_page' => -1,
580 'post_status' => 'publish',
581 ]
582 )
583 );
584
585 $options = [];
586
587 foreach ( $forms as $form ) {
588 if ( $form instanceof WP_Post ) {
589 if ( 'all' === $key ) {
590 $options[ $form->ID ] = $form;
591 } elseif ( ! empty( $key ) && is_string( $key ) && isset( $form->$key ) ) {
592 $options[ $form->ID ] = $form->$key;
593 } else {
594 $options[ $form->ID ] = $form->post_title;
595 }
596 }
597 }
598
599 return $options;
600 }
601
602 /**
603 * Get all the forms.
604 *
605 * @since 0.0.5
606 * @return array<mixed>
607 */
608 public static function get_sureforms_title_with_ids() {
609 $form_options = self::get_sureforms();
610
611 foreach ( $form_options as $key => $value ) {
612 $form_options[ $key ] = $value . ' #' . $key;
613 }
614
615 return $form_options;
616 }
617
618 /**
619 * Get the CSS variables based on different field spacing sizes.
620 *
621 * @param string|null $field_spacing The field spacing size or boolean false to return complete sizes array.
622 *
623 * @since 0.0.7
624 * @return array<string|mixed>
625 */
626 public static function get_css_vars( $field_spacing = null ) {
627 /**
628 * $sizes - Field Spacing Sizes Variables.
629 * The array contains the CSS variables for different field spacing sizes.
630 * Each key corresponds to the field spacing size, and the value is an array of CSS variables.
631 *
632 * For future variables depending on the field spacing size, add the variable to the array respectively.
633 */
634 $sizes = apply_filters(
635 'srfm_css_vars_sizes',
636 [
637 'small' => [
638 '--srfm-row-gap-between-blocks' => '16px',
639 // Address block gap and spacing variables.
640 '--srfm-col-gap-between-fields' => '12px',
641 '--srfm-row-gap-between-fields' => '12px',
642 '--srfm-gap-below-address-label' => '12px',
643 // Dropdown Variables.
644 '--srfm-dropdown-font-size' => '14px',
645 '--srfm-dropdown-gap-between-input-menu' => '4px',
646 '--srfm-dropdown-badge-padding' => '2px 6px',
647 '--srfm-dropdown-multiselect-font-size' => '12px',
648 '--srfm-dropdown-multiselect-line-height' => '16px',
649 '--srfm-dropdown-padding-right' => '12px',
650 // initial padding and from 20px - 12px for dropdown arrow width and 8px for gap before dropdown arrow.
651 '--srfm-dropdown-padding-right-icon' => 'calc( var( --srfm-dropdown-padding-right ) + 20px )',
652 '--srfm-dropdown-multiselect-padding' => '8px var( --srfm-dropdown-padding-right-icon ) 8px 8px',
653 // Input Field Variables.
654 '--srfm-input-height' => '40px',
655 '--srfm-input-field-padding' => '10px 12px',
656 '--srfm-input-field-font-size' => '14px',
657 '--srfm-input-field-line-height' => '20px',
658 '--srfm-input-field-margin' => '4px 0',
659 // Checkbox and GDPR Variables.
660 '--srfm-check-ctn-width' => '16px',
661 '--srfm-check-ctn-height' => '16px',
662 '--srfm-check-svg-size' => '10px',
663 '--srfm-checkbox-margin-top-frontend' => '2px',
664 '--srfm-checkbox-margin-top-editor' => '3px',
665 '--srfm-check-gap' => '8px',
666 '--srfm-checkbox-description-margin-left' => '24px',
667 // Phone Number field variables.
668 '--srfm-flag-section-padding' => '10px 0 10px 12px',
669 '--srfm-gap-between-icon-text' => '8px',
670 // Label Variables.
671 '--srfm-label-font-size' => '14px',
672 '--srfm-label-line-height' => '20px',
673 // Description Variables.
674 '--srfm-description-font-size' => '12px',
675 '--srfm-description-line-height' => '16px',
676 // Button Variables.
677 '--srfm-btn-padding' => '8px 14px',
678 '--srfm-btn-font-size' => '14px',
679 '--srfm-btn-line-height' => '20px',
680 // Multi Choice Variables.
681 '--srfm-multi-choice-horizontal-padding' => '16px',
682 '--srfm-multi-choice-vertical-padding' => '16px',
683 '--srfm-multi-choice-internal-option-gap' => '8px',
684 '--srfm-multi-choice-vertical-svg-size' => '32px',
685 '--srfm-multi-choice-horizontal-image-size' => '20px',
686 '--srfm-multi-choice-vertical-image-size' => '100px',
687 '--srfm-multi-choice-outer-padding' => '0',
688 ],
689 'medium' => [
690 '--srfm-row-gap-between-blocks' => '18px',
691 // Address block gap and spacing variables.
692 '--srfm-col-gap-between-fields' => '16px',
693 '--srfm-row-gap-between-fields' => '16px',
694 '--srfm-gap-below-address-label' => '14px',
695 // Input Field Variables.
696 '--srfm-input-height' => '44px',
697 '--srfm-input-field-font-size' => '16px',
698 '--srfm-input-field-line-height' => '24px',
699 '--srfm-input-field-margin' => '6px 0',
700 // Checkbox and GDPR Variables.
701 '--srfm-checkbox-margin-top-frontend' => '4px',
702 '--srfm-checkbox-margin-top-editor' => '6px',
703 '--srfm-checkbox-description-margin-left' => '24px',
704 // Label Variables.
705 '--srfm-label-font-size' => '16px',
706 '--srfm-label-line-height' => '24px',
707 // Description Variables.
708 '--srfm-description-font-size' => '14px',
709 '--srfm-description-line-height' => '20px',
710 // Button Variables.
711 '--srfm-btn-padding' => '10px 14px',
712 '--srfm-btn-font-size' => '16px',
713 '--srfm-btn-line-height' => '24px',
714 // Multi Choice Variables.
715 '--srfm-multi-choice-horizontal-padding' => '20px',
716 '--srfm-multi-choice-vertical-padding' => '20px',
717 '--srfm-multi-choice-vertical-svg-size' => '40px',
718 '--srfm-multi-choice-horizontal-image-size' => '24px',
719 '--srfm-multi-choice-vertical-image-size' => '120px',
720 '--srfm-multi-choice-outer-padding' => '2px',
721 ],
722 'large' => [
723 '--srfm-row-gap-between-blocks' => '20px',
724 // Address Block Gap and Spacing Variables.
725 '--srfm-col-gap-between-fields' => '16px',
726 '--srfm-row-gap-between-fields' => '20px',
727 '--srfm-gap-below-address-label' => '16px',
728 // Dropdown Variables.
729 '--srfm-dropdown-font-size' => '16px',
730 '--srfm-dropdown-gap-between-input-menu' => '6px',
731 '--srfm-dropdown-badge-padding' => '6px 6px',
732 '--srfm-dropdown-multiselect-font-size' => '14px',
733 '--srfm-dropdown-multiselect-line-height' => '20px',
734 '--srfm-dropdown-padding-right' => '14px',
735 // Input Field Variables.
736 '--srfm-input-height' => '48px',
737 '--srfm-input-field-padding' => '10px 14px',
738 '--srfm-input-field-font-size' => '18px',
739 '--srfm-input-field-line-height' => '28px',
740 '--srfm-input-field-margin' => '8px 0',
741 // Checkbox and GDPR Variables.
742 '--srfm-check-ctn-width' => '20px',
743 '--srfm-check-ctn-height' => '20px',
744 '--srfm-check-svg-size' => '14px',
745 '--srfm-check-gap' => '10px',
746 '--srfm-checkbox-margin-top-frontend' => '4px',
747 '--srfm-checkbox-margin-top-editor' => '5px',
748 '--srfm-checkbox-description-margin-left' => '30px',
749 // Label Variables.
750 '--srfm-label-font-size' => '18px',
751 '--srfm-label-line-height' => '28px',
752 // Description Variables.
753 '--srfm-description-font-size' => '16px',
754 '--srfm-description-line-height' => '24px',
755 // Button Variables.
756 '--srfm-btn-padding' => '10px 14px',
757 '--srfm-btn-font-size' => '18px',
758 '--srfm-btn-line-height' => '28px',
759 // Multi Choice Variables.
760 '--srfm-multi-choice-horizontal-padding' => '24px',
761 '--srfm-multi-choice-vertical-padding' => '24px',
762 '--srfm-multi-choice-internal-option-gap' => '12px',
763 '--srfm-multi-choice-vertical-svg-size' => '48px',
764 '--srfm-multi-choice-horizontal-image-size' => '28px',
765 '--srfm-multi-choice-vertical-image-size' => '140px',
766 '--srfm-multi-choice-outer-padding' => '4px',
767 ],
768 ]
769 );
770 // Return complete sizes array if field_spacing is false. Required in case of JS for Editor changes.
771 if ( ! $field_spacing ) {
772 return $sizes;
773 }
774
775 $selected_size = $sizes['small'];
776 if ( 'small' !== $field_spacing && isset( $sizes[ $field_spacing ] ) ) {
777 $selected_size = array_merge( $selected_size, $sizes[ $field_spacing ] );
778 }
779
780 return $selected_size;
781 }
782
783 /**
784 * Array of SureForms blocks which get have user input.
785 *
786 * @since 0.0.10
787 * @return array<string>
788 */
789 public static function get_sureforms_blocks() {
790 return apply_filters(
791 'srfm_blocks',
792 [
793 'srfm/input',
794 'srfm/email',
795 'srfm/textarea',
796 'srfm/number',
797 'srfm/checkbox',
798 'srfm/gdpr',
799 'srfm/phone',
800 'srfm/address',
801 'srfm/dropdown',
802 'srfm/multi-choice',
803 'srfm/radio',
804 'srfm/submit',
805 'srfm/url',
806 ]
807 );
808 }
809
810 /**
811 * Process blocks and inner blocks.
812 *
813 * @param array<array<array<mixed>>> $blocks The block data.
814 * @param array<string> $slugs The array of existing slugs.
815 * @param bool $updated The array of existing slugs.
816 * @param string $prefix The array of existing slugs.
817 * @param bool $skip_checking_existing_slug Skips the checking of existing slug if passed true. More information documented inside this function.
818 * @since 0.0.10
819 * @return array{array<array<array<mixed>>>,array<string>,bool}
820 */
821 public static function process_blocks( $blocks, &$slugs, &$updated, $prefix = '', $skip_checking_existing_slug = false ) {
822
823 if ( ! is_array( $blocks ) ) {
824 return [ $blocks, $slugs, $updated ];
825 }
826
827 foreach ( $blocks as $index => $block ) {
828
829 if ( ! is_array( $block ) ) {
830 continue;
831 }
832 // Checking only for SureForms blocks which can have user input.
833 if ( empty( $block['blockName'] ) || ! in_array( $block['blockName'], self::get_sureforms_blocks(), true ) ) {
834 continue;
835 }
836
837 /**
838 * Lets continue if slug already exists.
839 * This will ensure that we don't update already existing slugs.
840 */
841 if ( isset( $block['attrs'] ) && ! empty( $block['attrs']['slug'] ) && ! in_array( $block['attrs']['slug'], $slugs, true ) ) {
842
843 // Made it associative array, so that we can directly check it using block_id rather than mapping or using "in_array" for the checks.
844 $slugs[ $block['attrs']['block_id'] ] = self::get_string_value( $block['attrs']['slug'] );
845 continue;
846 }
847
848 if ( $skip_checking_existing_slug && empty( $block['innerBlocks'] ) && isset( $slugs[ $block['attrs']['block_id'] ] ) ) {
849 /**
850 * Skip re-processing of the already process or existing slugs if above parameter "$skip_checking_existing_slug" is passed as true.
851 * This is helpful in the scenarios where we need to compare and verify between already saved blocks and new unsaved blocks parsed
852 * from the contents.
853 *
854 * However, it is also necessary to make sure if that current block is not a parent / wrapper block
855 * by checking "$block['innerBlocks']" empty.
856 *
857 * And finally, checking if the block-id "$block['attrs']['block_id']" is already set in the list of "$slugs",
858 * making sure that we are only processing the new blocks.
859 */
860 continue;
861 }
862
863 if ( is_array( $blocks[ $index ]['attrs'] ) ) {
864
865 $blocks[ $index ]['attrs']['slug'] = self::generate_unique_block_slug( $block, $slugs, $prefix );
866 $slugs[ $block['attrs']['block_id'] ] = $blocks[ $index ]['attrs']['slug']; // Made it associative array, so that we can directly check it using block_id rather than mapping or using "in_array" for the checks.
867 $updated = true;
868 if ( is_array( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) ) {
869
870 [ $blocks[ $index ]['innerBlocks'], $slugs, $updated ] = self::process_blocks( $block['innerBlocks'], $slugs, $updated, $blocks[ $index ]['attrs']['slug'] );
871
872 }
873 }
874 }
875 return [ $blocks, $slugs, $updated ];
876 }
877
878 /**
879 * Generates slug based on the provided block and existing slugs.
880 *
881 * @param array<mixed> $block The block data.
882 * @param array<string> $slugs The array of existing slugs.
883 * @param string $prefix The array of existing slugs.
884 * @since 0.0.10
885 * @return string The generated unique block slug.
886 */
887 public static function generate_unique_block_slug( $block, $slugs, $prefix ) {
888 $slug = is_string( $block['blockName'] ) ? $block['blockName'] : '';
889
890 if ( ! empty( $block['attrs']['label'] ) && is_string( $block['attrs']['label'] ) ) {
891 $slug = sanitize_title( $block['attrs']['label'] );
892 }
893
894 if ( ! empty( $prefix ) ) {
895 $slug = $prefix . '-' . $slug;
896 }
897
898 return self::generate_slug( $slug, $slugs );
899 }
900
901 /**
902 * This function ensures that the slug is unique.
903 * If the slug is already taken, it appends a number to the slug to make it unique.
904 *
905 * @param string $slug test to be converted to slug.
906 * @param array<string> $slugs An array of existing slugs.
907 * @since 0.0.10
908 * @return string The unique slug.
909 */
910 public static function generate_slug( $slug, $slugs ) {
911 $slug = sanitize_title( $slug );
912
913 if ( ! in_array( $slug, $slugs, true ) ) {
914 return $slug;
915 }
916
917 $index = 1;
918
919 while ( in_array( $slug . '-' . $index, $slugs, true ) ) {
920 $index++;
921 }
922
923 return $slug . '-' . $index;
924 }
925
926 /**
927 * Encode data to JSON. This function will encode the data with JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE.
928 *
929 * @since 0.0.11
930 * @param array<mixed> $data The data to encode.
931 * @return string|false The JSON representation of the value on success or false on failure.
932 */
933 public static function encode_json( $data ) {
934 return wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
935 }
936
937 /**
938 * Returns true if SureTriggers plugin is ready for the custom app.
939 *
940 * @since 1.0.3
941 * @return bool Returns true if SureTriggers plugin is ready for the custom app.
942 */
943 public static function is_suretriggers_ready() {
944 if ( ! defined( 'SURE_TRIGGERS_FILE' ) ) {
945 // Probably plugin is de-activated or not installed at all.
946 return false;
947 }
948
949 $suretriggers_data = get_option( 'suretrigger_options', [] );
950 if ( ! is_array( $suretriggers_data ) || empty( $suretriggers_data['secret_key'] ) || ! is_string( $suretriggers_data['secret_key'] ) ) {
951 // SureTriggers is not authenticated yet.
952 return false;
953 }
954
955 return true;
956 }
957
958 /**
959 * Registers script translations for a specific handle.
960 *
961 * This function sets the script translations for a given script handle, allowing
962 * localization of JavaScript strings using the specified text domain and path.
963 *
964 * @param string $handle The script handle to apply translations to.
965 * @param string $domain Optional. The text domain for translations. Default is 'sureforms'.
966 * @param string $path Optional. The path to the translation files. Default is the 'languages' folder in the SureForms directory.
967 *
968 * @since 1.0.5
969 * @return void
970 */
971 public static function register_script_translations( $handle, $domain = 'sureforms', $path = SRFM_DIR . 'languages' ) {
972 wp_set_script_translations( $handle, $domain, $path );
973 }
974 }
975