PluginProbe
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz / 0.0.13
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz v0.0.13
2.12.7 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 All 97 releases
sureforms / inc / helper.php

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

954 lines 32.2 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 if ( false === strpos( $key, '-lbl-' ) ) {
571 continue;
572 }
573 $label = explode( '-lbl-', $key )[1];
574 $slug = implode( '-', array_slice( explode( '-', $label ), 1 ) );
575 $mapped_data[ $slug ] = $value;
576 }
577 return $mapped_data;
578 }
579
580 /**
581 * Get forms options. Shows all the available forms in the dropdown.
582 *
583 * @since 0.0.5
584 * @param string $key Determines the type of data to return.
585 * @return array<mixed>
586 */
587 public static function get_sureforms( $key = '' ) {
588 $forms = get_posts(
589 apply_filters(
590 'srfm_get_sureforms_query_args',
591 [
592 'post_type' => SRFM_FORMS_POST_TYPE,
593 'posts_per_page' => -1,
594 'post_status' => 'publish',
595 ]
596 )
597 );
598
599 $options = [];
600
601 foreach ( $forms as $form ) {
602 if ( $form instanceof WP_Post ) {
603 if ( 'all' === $key ) {
604 $options[ $form->ID ] = $form;
605 } elseif ( ! empty( $key ) && is_string( $key ) && isset( $form->$key ) ) {
606 $options[ $form->ID ] = $form->$key;
607 } else {
608 $options[ $form->ID ] = $form->post_title;
609 }
610 }
611 }
612
613 return $options;
614 }
615
616 /**
617 * Get all the forms.
618 *
619 * @since 0.0.5
620 * @return array<mixed>
621 */
622 public static function get_sureforms_title_with_ids() {
623 $form_options = self::get_sureforms();
624
625 foreach ( $form_options as $key => $value ) {
626 $form_options[ $key ] = $value . ' #' . $key;
627 }
628
629 return $form_options;
630 }
631
632 /**
633 * Get the CSS variables based on different field spacing sizes.
634 *
635 * @param string|null $field_spacing The field spacing size or boolean false to return complete sizes array.
636 *
637 * @since 0.0.7
638 * @return array<string|mixed>
639 */
640 public static function get_css_vars( $field_spacing = null ) {
641 /**
642 * $sizes - Field Spacing Sizes Variables.
643 * The array contains the CSS variables for different field spacing sizes.
644 * Each key corresponds to the field spacing size, and the value is an array of CSS variables.
645 *
646 * For future variables depending on the field spacing size, add the variable to the array respectively.
647 */
648 $sizes = apply_filters(
649 'srfm_css_vars_sizes',
650 [
651 'small' => [
652 '--srfm-row-gap-between-blocks' => '16px',
653 // Address block gap and spacing variables.
654 '--srfm-col-gap-between-fields' => '12px',
655 '--srfm-row-gap-between-fields' => '12px',
656 '--srfm-gap-below-address-label' => '12px',
657 // Dropdown Variables.
658 '--srfm-dropdown-font-size' => '14px',
659 '--srfm-dropdown-gap-between-input-menu' => '4px',
660 '--srfm-dropdown-badge-padding' => '2px 6px',
661 '--srfm-dropdown-multiselect-font-size' => '12px',
662 '--srfm-dropdown-multiselect-line-height' => '16px',
663 '--srfm-dropdown-padding-right' => '12px',
664 // initial padding and from 20px - 12px for dropdown arrow width and 8px for gap before dropdown arrow.
665 '--srfm-dropdown-padding-right-icon' => 'calc( var( --srfm-dropdown-padding-right ) + 20px )',
666 '--srfm-dropdown-multiselect-padding' => '8px var( --srfm-dropdown-padding-right-icon ) 8px 8px',
667 // Input Field Variables.
668 '--srfm-input-height' => '40px',
669 '--srfm-input-field-padding' => '10px 12px',
670 '--srfm-input-field-font-size' => '14px',
671 '--srfm-input-field-line-height' => '20px',
672 '--srfm-input-field-margin' => '4px 0',
673 // Checkbox and GDPR Variables.
674 '--srfm-check-ctn-width' => '16px',
675 '--srfm-check-ctn-height' => '16px',
676 '--srfm-check-svg-size' => '10px',
677 '--srfm-checkbox-margin-top-frontend' => '2px',
678 '--srfm-checkbox-margin-top-editor' => '3px',
679 '--srfm-check-gap' => '8px',
680 '--srfm-checkbox-description-margin-left' => '24px',
681 // Phone Number field variables.
682 '--srfm-flag-section-padding' => '10px 0 10px 12px',
683 '--srfm-gap-between-icon-text' => '8px',
684 // Label Variables.
685 '--srfm-label-font-size' => '14px',
686 '--srfm-label-line-height' => '20px',
687 // Description Variables.
688 '--srfm-description-font-size' => '12px',
689 '--srfm-description-line-height' => '16px',
690 // Button Variables.
691 '--srfm-btn-padding' => '8px 14px',
692 '--srfm-btn-font-size' => '14px',
693 '--srfm-btn-line-height' => '20px',
694 // Multi Choice Variables.
695 '--srfm-multi-choice-horizontal-padding' => '16px',
696 '--srfm-multi-choice-vertical-padding' => '16px',
697 '--srfm-multi-choice-internal-option-gap' => '8px',
698 '--srfm-multi-choice-vertical-svg-size' => '32px',
699 '--srfm-multi-choice-horizontal-image-size' => '20px',
700 '--srfm-multi-choice-vertical-image-size' => '100px',
701 '--srfm-multi-choice-outer-padding' => '0',
702 ],
703 'medium' => [
704 '--srfm-row-gap-between-blocks' => '18px',
705 // Address block gap and spacing variables.
706 '--srfm-col-gap-between-fields' => '16px',
707 '--srfm-row-gap-between-fields' => '16px',
708 '--srfm-gap-below-address-label' => '14px',
709 // Input Field Variables.
710 '--srfm-input-height' => '44px',
711 '--srfm-input-field-font-size' => '16px',
712 '--srfm-input-field-line-height' => '24px',
713 '--srfm-input-field-margin' => '6px 0',
714 // Checkbox and GDPR Variables.
715 '--srfm-checkbox-margin-top-frontend' => '4px',
716 '--srfm-checkbox-margin-top-editor' => '6px',
717 '--srfm-checkbox-description-margin-left' => '24px',
718 // Label Variables.
719 '--srfm-label-font-size' => '16px',
720 '--srfm-label-line-height' => '24px',
721 // Description Variables.
722 '--srfm-description-font-size' => '14px',
723 '--srfm-description-line-height' => '20px',
724 // Button Variables.
725 '--srfm-btn-padding' => '10px 14px',
726 '--srfm-btn-font-size' => '16px',
727 '--srfm-btn-line-height' => '24px',
728 // Multi Choice Variables.
729 '--srfm-multi-choice-horizontal-padding' => '20px',
730 '--srfm-multi-choice-vertical-padding' => '20px',
731 '--srfm-multi-choice-vertical-svg-size' => '40px',
732 '--srfm-multi-choice-horizontal-image-size' => '24px',
733 '--srfm-multi-choice-vertical-image-size' => '120px',
734 '--srfm-multi-choice-outer-padding' => '2px',
735 ],
736 'large' => [
737 '--srfm-row-gap-between-blocks' => '20px',
738 // Address Block Gap and Spacing Variables.
739 '--srfm-col-gap-between-fields' => '16px',
740 '--srfm-row-gap-between-fields' => '20px',
741 '--srfm-gap-below-address-label' => '16px',
742 // Dropdown Variables.
743 '--srfm-dropdown-font-size' => '16px',
744 '--srfm-dropdown-gap-between-input-menu' => '6px',
745 '--srfm-dropdown-badge-padding' => '6px 6px',
746 '--srfm-dropdown-multiselect-font-size' => '14px',
747 '--srfm-dropdown-multiselect-line-height' => '20px',
748 '--srfm-dropdown-padding-right' => '14px',
749 // Input Field Variables.
750 '--srfm-input-height' => '48px',
751 '--srfm-input-field-padding' => '10px 14px',
752 '--srfm-input-field-font-size' => '18px',
753 '--srfm-input-field-line-height' => '28px',
754 '--srfm-input-field-margin' => '8px 0',
755 // Checkbox and GDPR Variables.
756 '--srfm-check-ctn-width' => '20px',
757 '--srfm-check-ctn-height' => '20px',
758 '--srfm-check-svg-size' => '14px',
759 '--srfm-check-gap' => '10px',
760 '--srfm-checkbox-margin-top-frontend' => '4px',
761 '--srfm-checkbox-margin-top-editor' => '5px',
762 '--srfm-checkbox-description-margin-left' => '30px',
763 // Label Variables.
764 '--srfm-label-font-size' => '18px',
765 '--srfm-label-line-height' => '28px',
766 // Description Variables.
767 '--srfm-description-font-size' => '16px',
768 '--srfm-description-line-height' => '24px',
769 // Button Variables.
770 '--srfm-btn-padding' => '10px 14px',
771 '--srfm-btn-font-size' => '18px',
772 '--srfm-btn-line-height' => '28px',
773 // Multi Choice Variables.
774 '--srfm-multi-choice-horizontal-padding' => '24px',
775 '--srfm-multi-choice-vertical-padding' => '24px',
776 '--srfm-multi-choice-internal-option-gap' => '12px',
777 '--srfm-multi-choice-vertical-svg-size' => '48px',
778 '--srfm-multi-choice-horizontal-image-size' => '28px',
779 '--srfm-multi-choice-vertical-image-size' => '140px',
780 '--srfm-multi-choice-outer-padding' => '4px',
781 ],
782 ]
783 );
784 // Return complete sizes array if field_spacing is false. Required in case of JS for Editor changes.
785 if ( ! $field_spacing ) {
786 return $sizes;
787 }
788
789 $selected_size = $sizes['small'];
790 if ( 'small' !== $field_spacing && isset( $sizes[ $field_spacing ] ) ) {
791 $selected_size = array_merge( $selected_size, $sizes[ $field_spacing ] );
792 }
793
794 return $selected_size;
795 }
796
797 /**
798 * Array of SureForms blocks which get have user input.
799 *
800 * @since 0.0.10
801 * @return array<string>
802 */
803 public static function get_sureforms_blocks() {
804 return apply_filters(
805 'srfm_blocks',
806 [
807 'srfm/input',
808 'srfm/email',
809 'srfm/textarea',
810 'srfm/number',
811 'srfm/checkbox',
812 'srfm/gdpr',
813 'srfm/phone',
814 'srfm/address',
815 'srfm/dropdown',
816 'srfm/multi-choice',
817 'srfm/radio',
818 'srfm/submit',
819 'srfm/url',
820 ]
821 );
822 }
823
824 /**
825 * Process blocks and inner blocks.
826 *
827 * @param array<array<array<mixed>>> $blocks The block data.
828 * @param array<string> $slugs The array of existing slugs.
829 * @param bool $updated The array of existing slugs.
830 * @param string $prefix The array of existing slugs.
831 * @param boolean $skip_checking_existing_slug Skips the checking of existing slug if passed true. More information documented inside this function.
832 * @since 0.0.10
833 * @return array{array<array<array<mixed>>>,array<string>,bool}
834 */
835 public static function process_blocks( $blocks, &$slugs, &$updated, $prefix = '', $skip_checking_existing_slug = false ) {
836
837 if ( ! is_array( $blocks ) ) {
838 return [ $blocks, $slugs, $updated ];
839 }
840
841 foreach ( $blocks as $index => $block ) {
842
843 if ( ! is_array( $block ) ) {
844 continue;
845 }
846 // Checking only for SureForms blocks which can have user input.
847 if ( empty( $block['blockName'] ) || ! in_array( $block['blockName'], self::get_sureforms_blocks(), true ) ) {
848 continue;
849 }
850
851 /**
852 * Lets continue if slug already exists.
853 * This will ensure that we don't update already existing slugs.
854 */
855 if ( isset( $block['attrs'] ) && ! empty( $block['attrs']['slug'] ) && ! in_array( $block['attrs']['slug'], $slugs, true ) ) {
856
857 // Made it associative array, so that we can directly check it using block_id rather than mapping or using "in_array" for the checks.
858 $slugs[ $block['attrs']['block_id'] ] = self::get_string_value( $block['attrs']['slug'] );
859 continue;
860 }
861
862 if ( $skip_checking_existing_slug && empty( $block['innerBlocks'] ) && isset( $slugs[ $block['attrs']['block_id'] ] ) ) {
863 /**
864 * Skip re-processing of the already process or existing slugs if above parameter "$skip_checking_existing_slug" is passed as true.
865 * This is helpful in the scenarios where we need to compare and verify between already saved blocks and new unsaved blocks parsed
866 * from the contents.
867 *
868 * However, it is also necessary to make sure if that current block is not a parent / wrapper block
869 * by checking "$block['innerBlocks']" empty.
870 *
871 * And finally, checking if the block-id "$block['attrs']['block_id']" is already set in the list of "$slugs",
872 * making sure that we are only processing the new blocks.
873 */
874 continue;
875 }
876
877 if ( is_array( $blocks[ $index ]['attrs'] ) ) {
878
879 $blocks[ $index ]['attrs']['slug'] = self::generate_unique_block_slug( $block, $slugs, $prefix );
880 $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.
881 $updated = true;
882 if ( is_array( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) ) {
883
884 list( $blocks[ $index ]['innerBlocks'], $slugs, $updated ) = self::process_blocks( $block['innerBlocks'], $slugs, $updated, $blocks[ $index ]['attrs']['slug'] );
885
886 }
887 }
888 }
889 return [ $blocks, $slugs, $updated ];
890 }
891
892 /**
893 * Generates slug based on the provided block and existing slugs.
894 *
895 * @param array<mixed> $block The block data.
896 * @param array<string> $slugs The array of existing slugs.
897 * @param string $prefix The array of existing slugs.
898 * @since 0.0.10
899 * @return string The generated unique block slug.
900 */
901 public static function generate_unique_block_slug( $block, $slugs, $prefix ) {
902 $slug = is_string( $block['blockName'] ) ? $block['blockName'] : '';
903
904 if ( ! empty( $block['attrs']['label'] ) && is_string( $block['attrs']['label'] ) ) {
905 $slug = sanitize_title( $block['attrs']['label'] );
906 }
907
908 if ( ! empty( $prefix ) ) {
909 $slug = $prefix . '-' . $slug;
910 }
911
912 $slug = self::generate_slug( $slug, $slugs );
913
914 return $slug;
915 }
916
917 /**
918 * This function ensures that the slug is unique.
919 * If the slug is already taken, it appends a number to the slug to make it unique.
920 *
921 * @param string $slug test to be converted to slug.
922 * @param array<string> $slugs An array of existing slugs.
923 * @since 0.0.10
924 * @return string The unique slug.
925 */
926 public static function generate_slug( $slug, $slugs ) {
927 $slug = sanitize_title( $slug );
928
929 if ( ! in_array( $slug, $slugs, true ) ) {
930 return $slug;
931 }
932
933 $index = 1;
934
935 while ( in_array( $slug . '-' . $index, $slugs, true ) ) {
936 $index++;
937 }
938
939 return $slug . '-' . $index;
940 }
941
942 /**
943 * Encode data to JSON. This function will encode the data with JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE.
944 *
945 * @since 0.0.11
946 * @param array<mixed> $data The data to encode.
947 * @return string|false The JSON representation of the value on success or false on failure.
948 */
949 public static function encode_json( $data ) {
950 return wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
951 }
952
953 }
954