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