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