PluginProbe
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz / 0.0.11
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz v0.0.11
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 0.0.11, at inc/helper.php

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