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

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

1,252 lines 43.6 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 * Allowed HTML tags for SVG.
31 *
32 * @var array<string, array<string, bool>>
33 */
34 public static $allowed_tags_svg = [
35 'span' => [
36 'class' => true,
37 'aria-hidden' => true,
38 ],
39 'svg' => [
40 'xmlns' => true,
41 'width' => true,
42 'height' => true,
43 'viewBox' => true,
44 'fill' => true,
45 ],
46 'path' => [
47 'd' => true,
48 'stroke' => true,
49 'stroke-opacity' => true,
50 'stroke-width' => true,
51 'stroke-linecap' => true,
52 'stroke-linejoin' => true,
53 ],
54 ];
55
56 /**
57 * Sureforms SVGs.
58 *
59 * @var mixed srfm_svgs
60 */
61 private static $srfm_svgs = null;
62
63 /**
64 * Get common error message.
65 *
66 * @since 0.0.2
67 * @return array<string>
68 */
69 public static function get_common_err_msg() {
70 return [
71 'required' => __( 'This field is required.', 'sureforms' ),
72 'unique' => __( 'Value needs to be unique.', 'sureforms' ),
73 ];
74 }
75
76 /**
77 * Convert a file URL to a file path.
78 *
79 * @param string $file_url The URL of the file.
80 *
81 * @since 1.3.0
82 * @return string The file path.
83 */
84 public static function convert_fileurl_to_filepath( $file_url ) {
85 static $upload_dir = null;
86 if ( ! $upload_dir ) {
87 // Internally cache the upload directory.
88 $upload_dir = wp_get_upload_dir();
89 }
90 return wp_normalize_path( str_replace( $upload_dir['baseurl'], $upload_dir['basedir'], $file_url ) );
91 }
92
93 /**
94 * Checks if current value is string or else returns default value
95 *
96 * @param mixed $data data which need to be checked if is string.
97 *
98 * @since 0.0.1
99 * @return string
100 */
101 public static function get_string_value( $data ) {
102 if ( is_scalar( $data ) ) {
103 return (string) $data;
104 }
105 if ( is_object( $data ) && method_exists( $data, '__toString' ) ) {
106 return $data->__toString();
107 }
108 if ( is_null( $data ) ) {
109 return '';
110 }
111 return '';
112 }
113 /**
114 * Checks if current value is number or else returns default value
115 *
116 * @param mixed $value data which need to be checked if is string.
117 * @param int $base value can be set is $data is not a string, defaults to empty string.
118 *
119 * @since 0.0.1
120 * @return int
121 */
122 public static function get_integer_value( $value, $base = 10 ) {
123 if ( is_numeric( $value ) ) {
124 return (int) $value;
125 }
126 if ( is_string( $value ) ) {
127 $trimmed_value = trim( $value );
128 return intval( $trimmed_value, $base );
129 }
130 return 0;
131 }
132
133 /**
134 * Checks if current value is an array or else returns default value
135 *
136 * @param mixed $data Data which needs to be checked if it is an array.
137 *
138 * @since 0.0.3
139 * @return array
140 */
141 public static function get_array_value( $data ) {
142 if ( is_array( $data ) ) {
143 return $data;
144 }
145 if ( is_null( $data ) ) {
146 return [];
147 }
148 return (array) $data;
149 }
150
151 /**
152 * Extracts the field type from the dynamic field key ( or field slug ).
153 *
154 * @param string $field_key Dynamic field key.
155 * @since 0.0.6
156 * @return string Extracted field type.
157 */
158 public static function get_field_type_from_key( $field_key ) {
159
160 if ( false === strpos( $field_key, '-lbl-' ) ) {
161 return '';
162 }
163
164 return trim( explode( '-', $field_key )[1] );
165 }
166
167 /**
168 * Extracts the field label from the dynamic field key ( or field slug ).
169 *
170 * @param string $field_key Dynamic field key.
171 * @since 1.1.1
172 * @return string Extracted field label.
173 */
174 public static function get_field_label_from_key( $field_key ) {
175 if ( false === strpos( $field_key, '-lbl-' ) ) {
176 return '';
177 }
178
179 $label = explode( '-lbl-', $field_key )[1];
180 // Getting the encrypted label. we are removing the block slug here.
181 $label = explode( '-', $label )[0];
182
183 return $label ? html_entity_decode( self::decrypt( $label ) ) : '';
184 }
185
186 /**
187 * Extracts the block ID from the dynamic field key ( or field slug ).
188 *
189 * @param string $field_key Dynamic field key.
190 * @since 1.6.1
191 * @return string Extracted block ID.
192 */
193 public static function get_block_id_from_key( $field_key ) {
194 // Check if the key contains the block ID identifier.
195 if ( strpos( $field_key, 'srfm-' ) === 0 && strpos( $field_key, '-lbl-' ) === false ) {
196 return ''; // Return empty if the key format is invalid.
197 }
198
199 $parts = explode( '-lbl-', $field_key );
200 if ( isset( $parts[0] ) ) {
201 $block_id = explode( '-', $parts[0] );
202 if ( is_array( $block_id ) && ! empty( $block_id ) ) {
203 return end( $block_id );
204 }
205 }
206 return '';
207 }
208
209 /**
210 * Returns the proper sanitize callback functions according to the field type.
211 *
212 * @param string $field_type HTML field type.
213 * @since 0.0.6
214 * @return callable Returns sanitize callbacks according to the provided field type.
215 */
216 public static function get_field_type_sanitize_function( $field_type ) {
217 $callbacks = apply_filters(
218 'srfm_field_type_sanitize_functions',
219 [
220 'url' => 'esc_url_raw',
221 'input' => 'sanitize_text_field',
222 'number' => [ self::class, 'sanitize_number' ],
223 'email' => 'sanitize_email',
224 'textarea' => 'sanitize_textarea_field',
225 ]
226 );
227
228 return $callbacks[ $field_type ] ?? 'sanitize_text_field';
229 }
230
231 /**
232 * Sanitizes a numeric value.
233 *
234 * This function checks if the input value is numeric. If it is numeric, it sanitizes
235 * the value to ensure it's a float or integer, allowing for fractions and thousand separators.
236 * If the value is not numeric, it sanitizes it as a text field.
237 *
238 * @param mixed $value The value to be sanitized.
239 * @since 0.0.6
240 * @return int|float|string The sanitized value.
241 */
242 public static function sanitize_number( $value ) {
243 if ( ! is_numeric( $value ) ) {
244 // phpcs:ignore /** @phpstan-ignore-next-line */
245 return sanitize_text_field( $value ); // If it is not numeric, then let user get some sanitized data to view.
246 }
247
248 // phpcs:ignore /** @phpstan-ignore-next-line */
249 return sanitize_text_field( filter_var( $value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND ) );
250 }
251
252 /**
253 * This function sanitizes the submitted form data according to the field type.
254 *
255 * @param array<mixed> $form_data $form_data User submitted form data.
256 * @since 0.0.6
257 * @return array<mixed> $result Sanitized form data.
258 */
259 public static function sanitize_by_field_type( $form_data ) {
260 $result = [];
261
262 if ( empty( $form_data ) || ! is_array( $form_data ) ) {
263 return $result;
264 }
265
266 foreach ( $form_data as $field_key => &$value ) {
267 $field_type = self::get_field_type_from_key( $field_key );
268 $sanitize_function = self::get_field_type_sanitize_function( $field_type );
269 $sanitized_data = is_array( $value ) ? self::sanitize_by_field_type( $value ) : call_user_func( $sanitize_function, $value );
270
271 $result[ $field_key ] = $sanitized_data;
272 }
273
274 return $result;
275 }
276
277 /**
278 * This function performs array_map for multi dimensional array
279 *
280 * @param string $function function name to be applied on each element on array.
281 * @param array<mixed> $data_array array on which function needs to be performed.
282 * @return array<mixed>
283 * @since 0.0.1
284 */
285 public static function sanitize_recursively( $function, $data_array ) {
286 $response = [];
287 if ( is_array( $data_array ) ) {
288 if ( ! is_callable( $function ) ) {
289 return $data_array;
290 }
291 foreach ( $data_array as $key => $data ) {
292 $val = is_array( $data ) ? self::sanitize_recursively( $function, $data ) : $function( $data );
293 $response[ $key ] = $val;
294 }
295 }
296
297 return $response;
298 }
299
300 /**
301 * Generates common markup liked label, etc
302 *
303 * @param int|string $form_id form id.
304 * @param string $type Type of form markup.
305 * @param string $label Label for the form markup.
306 * @param string $slug Slug for the form markup.
307 * @param string $block_id Block id for the form markup.
308 * @param bool $required If field is required or not.
309 * @param string $help Help for the form markup.
310 * @param string $error_msg Error message for the form markup.
311 * @param bool $is_unique Check if the field is unique.
312 * @param string $duplicate_msg Duplicate message for field.
313 * @param bool $override Override for error markup.
314 * @return string
315 * @since 0.0.1
316 */
317 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 ) {
318 $duplicate_msg = $duplicate_msg ? ' data-unique-msg="' . esc_attr( $duplicate_msg ) . '"' : '';
319
320 $markup = '';
321 $show_labels_as_placeholder = get_post_meta( self::get_integer_value( $form_id ), '_srfm_use_label_as_placeholder', true );
322 $show_labels_as_placeholder = $show_labels_as_placeholder ? self::get_string_value( $show_labels_as_placeholder ) : false;
323
324 switch ( $type ) {
325 case 'label':
326 $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>' : '';
327 break;
328 case 'help':
329 $markup = $help ? '<div class="srfm-description" id="srfm-description-' . esc_attr( $block_id ) . '">' . wp_kses_post( htmlspecialchars_decode( $help ) ) . '</div>' : '';
330 break;
331 case 'error':
332 $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>' : '';
333 break;
334 case 'is_unique':
335 $markup = $is_unique ? '<div class="srfm-error">' . esc_html( $duplicate_msg ) . '</div>' : '';
336 break;
337 case 'placeholder':
338 $markup = $label && '1' === $show_labels_as_placeholder ? htmlspecialchars_decode( esc_html( $label ) ) . ( $required ? ' *' : '' ) : '';
339 break;
340 case 'label_text':
341 // This has been added for generating label text for the form markup instead of adding it in the label tag.
342 $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>' : '';
343 break;
344 default:
345 $markup = '';
346 }
347
348 return $markup;
349 }
350
351 /**
352 * Get an SVG Icon
353 *
354 * @since 0.0.1
355 * @param string $icon the icon name.
356 * @param string $class if the baseline class should be added.
357 * @param string $html Custom attributes inside svg wrapper.
358 * @return string
359 */
360 public static function fetch_svg( $icon = '', $class = '', $html = '' ) {
361 $class = $class ? ' ' . $class : '';
362
363 $output = '<span class="srfm-icon' . $class . '" ' . $html . '>';
364 if ( ! self::$srfm_svgs ) {
365 ob_start();
366
367 include_once SRFM_DIR . 'assets/svg/svgs.json';
368 self::$srfm_svgs = json_decode( self::get_string_value( ob_get_clean() ), true );
369 self::$srfm_svgs = apply_filters( 'srfm_svg_icons', self::$srfm_svgs );
370 }
371
372 $output .= self::$srfm_svgs[ $icon ] ?? '';
373 $output .= '</span>';
374
375 return $output;
376 }
377
378 /**
379 * Encrypt data using base64.
380 *
381 * @param string $input The input string which needs to be encrypted.
382 * @since 0.0.1
383 * @return string The encrypted string.
384 */
385 public static function encrypt( $input ) {
386 // If the input is empty or not a string, then abandon ship.
387 if ( empty( $input ) || ! is_string( $input ) ) {
388 return '';
389 }
390
391 // Encrypt the input and return it.
392 $base_64 = base64_encode( $input ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
393 return rtrim( $base_64, '=' );
394 }
395
396 /**
397 * Decrypt data using base64.
398 *
399 * @param string $input The input string which needs to be decrypted.
400 * @since 0.0.1
401 * @return string The decrypted string.
402 */
403 public static function decrypt( $input ) {
404 // If the input is empty or not a string, then abandon ship.
405 if ( empty( $input ) || ! is_string( $input ) ) {
406 return '';
407 }
408
409 // Decrypt the input and return it.
410 $base_64 = $input . str_repeat( '=', strlen( $input ) % 4 );
411 return base64_decode( $base_64 ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
412 }
413
414 /**
415 * Update an option from the database.
416 *
417 * @param string $key The option key.
418 * @param mixed $value The value to update.
419 * @param bool $network_override Whether to allow the network_override admin setting to be overridden on subsites.
420 * @since 0.0.1
421 * @return bool True if the option was updated, false otherwise.
422 */
423 public static function update_admin_settings_option( $key, $value, $network_override = false ) {
424 // Update the site-wide option if we're in the network admin, and return the updated status.
425 return $network_override && is_multisite() ? update_site_option( $key, $value ) : update_option( $key, $value );
426 }
427
428 /**
429 * Update an option from the database.
430 *
431 * @param int|string $post_id post id / form id.
432 * @param string $key meta key name.
433 * @param bool $single single or multiple.
434 * @param mixed $default default value.
435 *
436 * @since 0.0.1
437 * @return string Meta value.
438 */
439 public static function get_meta_value( $post_id, $key, $single = true, $default = '' ) {
440 $srfm_live_mode_data = self::get_instant_form_live_data();
441
442 if ( isset( $srfm_live_mode_data[ $key ] ) ) {
443 // Give priority to live mode data if we have one set from the Instant Form.
444 return self::get_string_value( $srfm_live_mode_data[ $key ] );
445 }
446
447 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 );
448 }
449
450 /**
451 * Wrapper for the WordPress's get_post_meta function with the support for default values.
452 *
453 * @param int|string $post_id Post ID.
454 * @param string $key The meta key to retrieve.
455 * @param mixed $default Default value.
456 * @param bool $single Optional. Whether to return a single value.
457 * @since 0.0.8
458 * @return mixed Meta value.
459 */
460 public static function get_post_meta( $post_id, $key, $default = null, $single = true ) {
461 $meta_value = get_post_meta( self::get_integer_value( $post_id ), $key, $single );
462 return $meta_value ? $meta_value : $default;
463 }
464
465 /**
466 * Returns query params data for instant form live preview.
467 *
468 * @since 0.0.8
469 * @return array<mixed> Live preview data.
470 */
471 public static function get_instant_form_live_data() {
472 $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 -- Nonce verification is not needed here.
473
474 return $srfm_live_mode_data ? array_map(
475 // Normalize falsy values.
476 static function( $live_data ) {
477 return 'false' === $live_data ? false : $live_data;
478 },
479 $srfm_live_mode_data
480 ) : [];
481 }
482
483 /**
484 * Default dynamic block value.
485 *
486 * @since 0.0.1
487 * @return array<string> Meta value.
488 */
489 public static function default_dynamic_block_option() {
490
491 $common_err_msg = self::get_common_err_msg();
492
493 $default_values = [
494 'srfm_url_block_required_text' => $common_err_msg['required'],
495 'srfm_input_block_required_text' => $common_err_msg['required'],
496 'srfm_input_block_unique_text' => $common_err_msg['unique'],
497 'srfm_address_block_required_text' => $common_err_msg['required'],
498 'srfm_phone_block_required_text' => $common_err_msg['required'],
499 'srfm_phone_block_unique_text' => $common_err_msg['unique'],
500 'srfm_number_block_required_text' => $common_err_msg['required'],
501 'srfm_textarea_block_required_text' => $common_err_msg['required'],
502 'srfm_multi_choice_block_required_text' => $common_err_msg['required'],
503 'srfm_checkbox_block_required_text' => $common_err_msg['required'],
504 'srfm_gdpr_block_required_text' => $common_err_msg['required'],
505 'srfm_email_block_required_text' => $common_err_msg['required'],
506 'srfm_email_block_unique_text' => $common_err_msg['unique'],
507 'srfm_dropdown_block_required_text' => $common_err_msg['required'],
508 'srfm_rating_block_required_text' => $common_err_msg['required'],
509 ];
510
511 $default_values = array_merge( $default_values, Translatable::dynamic_validation_messages() );
512
513 return apply_filters( 'srfm_default_dynamic_block_option', $default_values, $common_err_msg );
514 }
515
516 /**
517 * Get default dynamic block value.
518 *
519 * @param string $key meta key name.
520 * @since 0.0.1
521 * @return string Meta value.
522 */
523 public static function get_default_dynamic_block_option( $key ) {
524 $default_dynamic_values = self::default_dynamic_block_option();
525 $option = get_option( 'srfm_default_dynamic_block_option', $default_dynamic_values );
526
527 if ( is_array( $option ) && array_key_exists( $key, $option ) ) {
528 return $option[ $key ];
529 }
530 return '';
531 }
532
533 /**
534 * Checks whether a given request has appropriate permissions.
535 *
536 * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
537 * @since 0.0.1
538 */
539 public static function get_items_permissions_check() {
540 if ( current_user_can( 'edit_posts' ) ) {
541 return true;
542 }
543
544 foreach ( get_post_types( [ 'show_in_rest' => true ], 'objects' ) as $post_type ) {
545 /**
546 * The post type.
547 *
548 * @var WP_Post_Type $post_type
549 */
550 if ( current_user_can( $post_type->cap->edit_posts ) ) {
551 return true;
552 }
553 }
554
555 return new WP_Error(
556 'rest_cannot_view',
557 __( 'Sorry, you are not allowed to perform this action.', 'sureforms' ),
558 [ 'status' => \rest_authorization_required_code() ]
559 );
560 }
561
562 /**
563 * Check if the current user has a given capability.
564 *
565 * @param string $capability The capability to check.
566 * @since 0.0.3
567 * @return bool Whether the current user has the given capability or role.
568 */
569 public static function current_user_can( $capability = '' ) {
570
571 if ( ! function_exists( 'current_user_can' ) ) {
572 return false;
573 }
574
575 if ( ! is_string( $capability ) || empty( $capability ) ) {
576 $capability = 'edit_posts';
577 }
578
579 return current_user_can( $capability );
580 }
581
582 /**
583 * Get all the entries for the given form ids. The entries are older than the given days_old.
584 *
585 * @param int $days_old The number of days old the entries should be.
586 * @param array<int> $sf_form_ids The form ids for which the entries need to be fetched.
587 * @since 0.0.2
588 * @return array<mixed> the entries matching the criteria.
589 */
590 public static function get_entries_from_form_ids( $days_old = 0, $sf_form_ids = [] ) {
591
592 $entries = [];
593 $days_old_date = ( new \DateTime() )->modify( "-{$days_old} days" )->format( 'Y-m-d H:i:s' );
594
595 foreach ( $sf_form_ids as $form_id ) {
596 // args according to the get_all() function in the Entries class.
597 $args = [
598 'where' => [
599 [
600 [
601 'key' => 'form_id',
602 'value' => $form_id,
603 'compare' => '=',
604 ],
605 [
606 'key' => 'created_at',
607 'value' => $days_old_date,
608 'compare' => '<=',
609 ],
610 ],
611 ],
612 ];
613
614 // store all the entries in a single array.
615 $entries = array_merge( $entries, Entries::get_all( $args, false ) );
616 }
617 return $entries;
618 }
619
620 /**
621 * Decode block attributes.
622 * The function reverses the effect of serialize_block_attributes()
623 *
624 * @link https://developer.wordpress.org/reference/functions/serialize_block_attributes/
625 * @param string $encoded_data the encoded block attribute.
626 * @since 0.0.2
627 * @return string decoded block attribute
628 */
629 public static function decode_block_attribute( $encoded_data = '' ) {
630 $decoded_data = preg_replace( '/\\\\u002d\\\\u002d/', '--', self::get_string_value( $encoded_data ) );
631 $decoded_data = preg_replace( '/\\\\u003c/', '<', self::get_string_value( $decoded_data ) );
632 $decoded_data = preg_replace( '/\\\\u003e/', '>', self::get_string_value( $decoded_data ) );
633 $decoded_data = preg_replace( '/\\\\u0026/', '&', self::get_string_value( $decoded_data ) );
634 $decoded_data = preg_replace( '/\\\\\\\\"/', '"', self::get_string_value( $decoded_data ) );
635 return self::get_string_value( $decoded_data );
636 }
637
638 /**
639 * Map slugs to submission data.
640 *
641 * @param array<mixed> $submission_data submission_data.
642 * @since 0.0.3
643 * @return array<mixed>
644 */
645 public static function map_slug_to_submission_data( $submission_data = [] ) {
646 $mapped_data = [];
647 foreach ( $submission_data as $key => $value ) {
648 if ( false === strpos( $key, '-lbl-' ) ) {
649 continue;
650 }
651 $label = explode( '-lbl-', $key )[1];
652 $slug = implode( '-', array_slice( explode( '-', $label ), 1 ) );
653 $mapped_data[ $slug ] = is_string( $value ) ? html_entity_decode( esc_attr( $value ) ) : $value;
654 }
655 return $mapped_data;
656 }
657
658 /**
659 * Get forms options. Shows all the available forms in the dropdown.
660 *
661 * @since 0.0.5
662 * @param string $key Determines the type of data to return.
663 * @return array<mixed>
664 */
665 public static function get_sureforms( $key = '' ) {
666 $forms = get_posts(
667 apply_filters(
668 'srfm_get_sureforms_query_args',
669 [
670 'post_type' => SRFM_FORMS_POST_TYPE,
671 'posts_per_page' => -1,
672 'post_status' => 'publish',
673 ]
674 )
675 );
676
677 $options = [];
678
679 foreach ( $forms as $form ) {
680 if ( $form instanceof WP_Post ) {
681 if ( 'all' === $key ) {
682 $options[ $form->ID ] = $form;
683 } elseif ( ! empty( $key ) && is_string( $key ) && isset( $form->$key ) ) {
684 $options[ $form->ID ] = $form->$key;
685 } else {
686 $options[ $form->ID ] = $form->post_title;
687 }
688 }
689 }
690
691 return $options;
692 }
693
694 /**
695 * Get all the forms.
696 *
697 * @since 0.0.5
698 * @return array<mixed>
699 */
700 public static function get_sureforms_title_with_ids() {
701 $form_options = self::get_sureforms();
702
703 foreach ( $form_options as $key => $value ) {
704 $form_options[ $key ] = $value . ' #' . $key;
705 }
706
707 return $form_options;
708 }
709
710 /**
711 * Get the CSS variables based on different field spacing sizes.
712 *
713 * @param string|null $field_spacing The field spacing size or boolean false to return complete sizes array.
714 *
715 * @since 0.0.7
716 * @return array<string|mixed>
717 */
718 public static function get_css_vars( $field_spacing = null ) {
719 /**
720 * $sizes - Field Spacing Sizes Variables.
721 * The array contains the CSS variables for different field spacing sizes.
722 * Each key corresponds to the field spacing size, and the value is an array of CSS variables.
723 *
724 * For future variables depending on the field spacing size, add the variable to the array respectively.
725 */
726 $sizes = apply_filters(
727 'srfm_css_vars_sizes',
728 [
729 'small' => [
730 '--srfm-row-gap-between-blocks' => '16px',
731 // Address block gap and spacing variables.
732 '--srfm-col-gap-between-fields' => '12px',
733 '--srfm-row-gap-between-fields' => '12px',
734 '--srfm-gap-below-address-label' => '12px',
735 // Dropdown Variables.
736 '--srfm-dropdown-font-size' => '14px',
737 '--srfm-dropdown-gap-between-input-menu' => '4px',
738 '--srfm-dropdown-badge-padding' => '2px 6px',
739 '--srfm-dropdown-multiselect-font-size' => '12px',
740 '--srfm-dropdown-multiselect-line-height' => '16px',
741 '--srfm-dropdown-padding-right' => '12px',
742 // initial padding and from 20px - 12px for dropdown arrow width and 8px for gap before dropdown arrow.
743 '--srfm-dropdown-padding-right-icon' => 'calc( var( --srfm-dropdown-padding-right ) + 20px )',
744 '--srfm-dropdown-multiselect-padding' => '8px var( --srfm-dropdown-padding-right-icon ) 8px 8px',
745 // Input Field Variables.
746 '--srfm-input-height' => '40px',
747 '--srfm-input-field-padding' => '10px 12px',
748 '--srfm-input-field-font-size' => '14px',
749 '--srfm-input-field-line-height' => '20px',
750 '--srfm-input-field-margin' => '4px 0',
751 // Checkbox and GDPR Variables.
752 '--srfm-check-ctn-width' => '16px',
753 '--srfm-check-ctn-height' => '16px',
754 '--srfm-check-svg-size' => '10px',
755 '--srfm-checkbox-margin-top-frontend' => '2px',
756 '--srfm-checkbox-margin-top-editor' => '3px',
757 '--srfm-check-gap' => '8px',
758 '--srfm-checkbox-description-margin-left' => '24px',
759 // Phone Number field variables.
760 '--srfm-flag-section-padding' => '10px 0 10px 12px',
761 '--srfm-gap-between-icon-text' => '8px',
762 // Label Variables.
763 '--srfm-label-font-size' => '14px',
764 '--srfm-label-line-height' => '20px',
765 // Description Variables.
766 '--srfm-description-font-size' => '12px',
767 '--srfm-description-line-height' => '16px',
768 // Button Variables.
769 '--srfm-btn-padding' => '8px 14px',
770 '--srfm-btn-font-size' => '14px',
771 '--srfm-btn-line-height' => '20px',
772 // Multi Choice Variables.
773 '--srfm-multi-choice-horizontal-padding' => '16px',
774 '--srfm-multi-choice-vertical-padding' => '16px',
775 '--srfm-multi-choice-internal-option-gap' => '8px',
776 '--srfm-multi-choice-vertical-svg-size' => '32px',
777 '--srfm-multi-choice-horizontal-image-size' => '20px',
778 '--srfm-multi-choice-vertical-image-size' => '100px',
779 '--srfm-multi-choice-outer-padding' => '0',
780 ],
781 'medium' => [
782 '--srfm-row-gap-between-blocks' => '18px',
783 // Address block gap and spacing variables.
784 '--srfm-col-gap-between-fields' => '16px',
785 '--srfm-row-gap-between-fields' => '16px',
786 '--srfm-gap-below-address-label' => '14px',
787 // Input Field Variables.
788 '--srfm-input-height' => '44px',
789 '--srfm-input-field-font-size' => '16px',
790 '--srfm-input-field-line-height' => '24px',
791 '--srfm-input-field-margin' => '6px 0',
792 // Checkbox and GDPR Variables.
793 '--srfm-checkbox-margin-top-frontend' => '4px',
794 '--srfm-checkbox-margin-top-editor' => '6px',
795 '--srfm-checkbox-description-margin-left' => '24px',
796 // Label Variables.
797 '--srfm-label-font-size' => '16px',
798 '--srfm-label-line-height' => '24px',
799 // Description Variables.
800 '--srfm-description-font-size' => '14px',
801 '--srfm-description-line-height' => '20px',
802 // Button Variables.
803 '--srfm-btn-padding' => '10px 14px',
804 '--srfm-btn-font-size' => '16px',
805 '--srfm-btn-line-height' => '24px',
806 // Multi Choice Variables.
807 '--srfm-multi-choice-horizontal-padding' => '20px',
808 '--srfm-multi-choice-vertical-padding' => '20px',
809 '--srfm-multi-choice-vertical-svg-size' => '40px',
810 '--srfm-multi-choice-horizontal-image-size' => '24px',
811 '--srfm-multi-choice-vertical-image-size' => '120px',
812 '--srfm-multi-choice-outer-padding' => '2px',
813 ],
814 'large' => [
815 '--srfm-row-gap-between-blocks' => '20px',
816 // Address Block Gap and Spacing Variables.
817 '--srfm-col-gap-between-fields' => '16px',
818 '--srfm-row-gap-between-fields' => '20px',
819 '--srfm-gap-below-address-label' => '16px',
820 // Dropdown Variables.
821 '--srfm-dropdown-font-size' => '16px',
822 '--srfm-dropdown-gap-between-input-menu' => '6px',
823 '--srfm-dropdown-badge-padding' => '6px 6px',
824 '--srfm-dropdown-multiselect-font-size' => '14px',
825 '--srfm-dropdown-multiselect-line-height' => '20px',
826 '--srfm-dropdown-padding-right' => '14px',
827 // Input Field Variables.
828 '--srfm-input-height' => '48px',
829 '--srfm-input-field-padding' => '10px 14px',
830 '--srfm-input-field-font-size' => '18px',
831 '--srfm-input-field-line-height' => '28px',
832 '--srfm-input-field-margin' => '8px 0',
833 // Checkbox and GDPR Variables.
834 '--srfm-check-ctn-width' => '20px',
835 '--srfm-check-ctn-height' => '20px',
836 '--srfm-check-svg-size' => '14px',
837 '--srfm-check-gap' => '10px',
838 '--srfm-checkbox-margin-top-frontend' => '4px',
839 '--srfm-checkbox-margin-top-editor' => '5px',
840 '--srfm-checkbox-description-margin-left' => '30px',
841 // Label Variables.
842 '--srfm-label-font-size' => '18px',
843 '--srfm-label-line-height' => '28px',
844 // Description Variables.
845 '--srfm-description-font-size' => '16px',
846 '--srfm-description-line-height' => '24px',
847 // Button Variables.
848 '--srfm-btn-padding' => '10px 14px',
849 '--srfm-btn-font-size' => '18px',
850 '--srfm-btn-line-height' => '28px',
851 // Multi Choice Variables.
852 '--srfm-multi-choice-horizontal-padding' => '24px',
853 '--srfm-multi-choice-vertical-padding' => '24px',
854 '--srfm-multi-choice-internal-option-gap' => '12px',
855 '--srfm-multi-choice-vertical-svg-size' => '48px',
856 '--srfm-multi-choice-horizontal-image-size' => '28px',
857 '--srfm-multi-choice-vertical-image-size' => '140px',
858 '--srfm-multi-choice-outer-padding' => '4px',
859 ],
860 ]
861 );
862 // Return complete sizes array if field_spacing is false. Required in case of JS for Editor changes.
863 if ( ! $field_spacing ) {
864 return $sizes;
865 }
866
867 $selected_size = $sizes['small'];
868 if ( 'small' !== $field_spacing && isset( $sizes[ $field_spacing ] ) ) {
869 $selected_size = array_merge( $selected_size, $sizes[ $field_spacing ] );
870 }
871
872 return $selected_size;
873 }
874
875 /**
876 * Array of SureForms blocks which get have user input.
877 *
878 * @since 0.0.10
879 * @return array<string>
880 */
881 public static function get_sureforms_blocks() {
882 return apply_filters(
883 'srfm_blocks',
884 [
885 'srfm/input',
886 'srfm/email',
887 'srfm/textarea',
888 'srfm/number',
889 'srfm/checkbox',
890 'srfm/gdpr',
891 'srfm/phone',
892 'srfm/address',
893 'srfm/dropdown',
894 'srfm/multi-choice',
895 'srfm/radio',
896 'srfm/submit',
897 'srfm/url',
898 ]
899 );
900 }
901
902 /**
903 * Process blocks and inner blocks.
904 *
905 * @param array<mixed> $blocks The block data.
906 * @param array<string> $slugs The array of existing slugs.
907 * @param bool $updated The array of existing slugs.
908 * @param string $prefix The array of existing slugs.
909 * @param bool $skip_checking_existing_slug Skips the checking of existing slug if passed true. More information documented inside this function.
910 * @since 0.0.10
911 * @return array
912 */
913 public static function process_blocks( $blocks, &$slugs, &$updated, $prefix = '', $skip_checking_existing_slug = false ) {
914
915 if ( ! is_array( $blocks ) ) {
916 return [ $blocks, $slugs, $updated ];
917 }
918
919 foreach ( $blocks as $index => $block ) {
920
921 if ( ! is_array( $block ) ) {
922 continue;
923 }
924 // Checking only for SureForms blocks which can have user input.
925 if ( empty( $block['blockName'] ) || ! in_array( $block['blockName'], self::get_sureforms_blocks(), true ) ) {
926 continue;
927 }
928
929 /**
930 * Lets continue if slug already exists.
931 * This will ensure that we don't update already existing slugs.
932 */
933 if ( isset( $block['attrs'] ) && ! empty( $block['attrs']['slug'] ) && ! in_array( $block['attrs']['slug'], $slugs, true ) ) {
934
935 // Made it associative array, so that we can directly check it using block_id rather than mapping or using "in_array" for the checks.
936 $slugs[ $block['attrs']['block_id'] ] = self::get_string_value( $block['attrs']['slug'] );
937 continue;
938 }
939
940 if ( $skip_checking_existing_slug && empty( $block['innerBlocks'] ) && isset( $slugs[ $block['attrs']['block_id'] ] ) ) {
941 /**
942 * Skip re-processing of the already process or existing slugs if above parameter "$skip_checking_existing_slug" is passed as true.
943 * This is helpful in the scenarios where we need to compare and verify between already saved blocks and new unsaved blocks parsed
944 * from the contents.
945 *
946 * However, it is also necessary to make sure if that current block is not a parent / wrapper block
947 * by checking "$block['innerBlocks']" empty.
948 *
949 * And finally, checking if the block-id "$block['attrs']['block_id']" is already set in the list of "$slugs",
950 * making sure that we are only processing the new blocks.
951 */
952 continue;
953 }
954
955 if ( is_array( $blocks[ $index ]['attrs'] ) ) {
956
957 $blocks[ $index ]['attrs']['slug'] = self::generate_unique_block_slug( $block, $slugs, $prefix );
958 $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.
959 $updated = true;
960 if ( is_array( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) ) {
961
962 [ $blocks[ $index ]['innerBlocks'], $slugs, $updated ] = self::process_blocks( $block['innerBlocks'], $slugs, $updated, $blocks[ $index ]['attrs']['slug'] );
963
964 }
965 }
966 }
967 return [ $blocks, $slugs, $updated ];
968 }
969
970 /**
971 * Generates slug based on the provided block and existing slugs.
972 *
973 * @param array<mixed> $block The block data.
974 * @param array<string> $slugs The array of existing slugs.
975 * @param string $prefix The array of existing slugs.
976 * @since 0.0.10
977 * @return string The generated unique block slug.
978 */
979 public static function generate_unique_block_slug( $block, $slugs, $prefix ) {
980 $slug = is_string( $block['blockName'] ) ? $block['blockName'] : '';
981
982 if ( ! empty( $block['attrs']['label'] ) && is_string( $block['attrs']['label'] ) ) {
983 $slug = sanitize_title( $block['attrs']['label'] );
984 }
985
986 if ( ! empty( $prefix ) ) {
987 $slug = $prefix . '-' . $slug;
988 }
989
990 return self::generate_slug( $slug, $slugs );
991 }
992
993 /**
994 * This function ensures that the slug is unique.
995 * If the slug is already taken, it appends a number to the slug to make it unique.
996 *
997 * @param string $slug test to be converted to slug.
998 * @param array<string> $slugs An array of existing slugs.
999 * @since 0.0.10
1000 * @return string The unique slug.
1001 */
1002 public static function generate_slug( $slug, $slugs ) {
1003 $slug = sanitize_title( $slug );
1004
1005 if ( ! in_array( $slug, $slugs, true ) ) {
1006 return $slug;
1007 }
1008
1009 $index = 1;
1010
1011 while ( in_array( $slug . '-' . $index, $slugs, true ) ) {
1012 $index++;
1013 }
1014
1015 return $slug . '-' . $index;
1016 }
1017
1018 /**
1019 * Encode data to JSON. This function will encode the data with JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE.
1020 *
1021 * @since 0.0.11
1022 * @param array<mixed> $data The data to encode.
1023 * @return string|false The JSON representation of the value on success or false on failure.
1024 */
1025 public static function encode_json( $data ) {
1026 return wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
1027 }
1028
1029 /**
1030 * Returns true if SureTriggers plugin is ready for the custom app.
1031 *
1032 * @since 1.0.3
1033 * @return bool Returns true if SureTriggers plugin is ready for the custom app.
1034 */
1035 public static function is_suretriggers_ready() {
1036 if ( ! defined( 'SURE_TRIGGERS_FILE' ) ) {
1037 // Probably plugin is de-activated or not installed at all.
1038 return false;
1039 }
1040
1041 $suretriggers_data = get_option( 'suretrigger_options', [] );
1042 if ( ! is_array( $suretriggers_data ) || empty( $suretriggers_data['secret_key'] ) || ! is_string( $suretriggers_data['secret_key'] ) ) {
1043 // SureTriggers is not authenticated yet.
1044 return false;
1045 }
1046
1047 return true;
1048 }
1049
1050 /**
1051 * Registers script translations for a specific handle.
1052 *
1053 * This function sets the script translations for a given script handle, allowing
1054 * localization of JavaScript strings using the specified text domain and path.
1055 *
1056 * @param string $handle The script handle to apply translations to.
1057 * @param string $domain Optional. The text domain for translations. Default is 'sureforms'.
1058 * @param string $path Optional. The path to the translation files. Default is the 'languages' folder in the SureForms directory.
1059 *
1060 * @since 1.0.5
1061 * @return void
1062 */
1063 public static function register_script_translations( $handle, $domain = 'sureforms', $path = SRFM_DIR . 'languages' ) {
1064 wp_set_script_translations( $handle, $domain, $path );
1065 }
1066
1067 /**
1068 * Validates whether the specified conditions or a single key-value pair exist in the request context.
1069 *
1070 * - If `$conditions` is provided as an array, it will validate all key-value pairs in `$conditions`
1071 * against the `$_REQUEST` superglobal.
1072 * - If `$conditions` is empty, it validates a single key-value pair from `$key` and `$value`.
1073 *
1074 * @param string $value The expected value to match in the request if `$conditions` is not used.
1075 * @param string $key The key to check for in the request if `$conditions` is not used.
1076 * @param array<string, string> $conditions An optional associative array of key-value pairs to validate.
1077 * @since 1.1.1
1078 * @return bool Returns true if all conditions are met or the single key-value pair is valid, otherwise false.
1079 */
1080 public static function validate_request_context( $value, $key = 'post_type', array $conditions = [] ) {
1081 // If conditions are provided, validate all key-value pairs in the conditions array.
1082 if ( ! empty( $conditions ) ) {
1083 foreach ( $conditions as $condition_key => $condition_value ) {
1084 if ( ! isset( $_REQUEST[ $condition_key ] ) || $_REQUEST[ $condition_key ] !== $condition_value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a controlled comparison of request values.
1085 // Return false if any condition is not satisfied.
1086 return false;
1087 }
1088 }
1089 // Return true if all conditions are satisfied.
1090 return true;
1091 }
1092
1093 // Validate $value and $key when no conditions are provided.
1094 if ( empty( $key ) || empty( $value ) ) {
1095 return false;
1096 }
1097
1098 // Validate a single key-value pair when no conditions are provided.
1099 return isset( $_REQUEST[ $key ] ) && $_REQUEST[ $key ] === $value; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification is not needed here. Input is validated via strict comparison.
1100 }
1101
1102 /**
1103 * Retrieve the list of excluded fields for form data processing.
1104 *
1105 * This method returns an array of field keys that should be excluded when
1106 * processing form data.
1107 *
1108 * @since 1.1.1
1109 * @return array<string> Returns the string array of excluded fields.
1110 */
1111 public static function get_excluded_fields() {
1112 $excluded_fields = [ 'srfm-honeypot-field', 'g-recaptcha-response', 'srfm-sender-email-field', 'form-id' ];
1113
1114 return apply_filters( 'srfm_excluded_fields', $excluded_fields );
1115 }
1116
1117 /**
1118 * Check whether the current page is a SureForms admin page.
1119 *
1120 * @since 1.2.2
1121 * @return bool Returns true if the current page is a SureForms admin page, otherwise false.
1122 */
1123 public static function is_sureforms_admin_page() {
1124 $current_screen = get_current_screen();
1125 $is_screen_sureforms_menu = self::validate_request_context( 'sureforms_menu', 'page' );
1126 $is_screen_add_new_form = self::validate_request_context( 'add-new-form', 'page' );
1127 $is_screen_sureforms_form_settings = self::validate_request_context( 'sureforms_form_settings', 'page' );
1128 $is_screen_sureforms_entries = self::validate_request_context( SRFM_ENTRIES, 'page' );
1129 $is_post_type_sureforms_form = $current_screen && SRFM_FORMS_POST_TYPE === $current_screen->post_type;
1130
1131 return $is_screen_sureforms_menu || $is_screen_add_new_form || $is_screen_sureforms_form_settings || $is_screen_sureforms_entries || $is_post_type_sureforms_form;
1132 }
1133
1134 /**
1135 * Filters and concatenates valid class names from an array.
1136 *
1137 * @param array<string> $class_names The array containing potential class names.
1138 * @since 1.4.0
1139 * @return string The concatenated string of valid class names separated by spaces.
1140 */
1141 public static function join_strings( $class_names ) {
1142 // Filter the array to include only valid class names.
1143 $valid_class_names = array_filter(
1144 $class_names,
1145 static function ( $value ) {
1146 return is_string( $value ) && '' !== $value && false !== $value;
1147 }
1148 );
1149
1150 // Concatenate the valid class names with spaces and return.
1151 return implode( ' ', $valid_class_names );
1152 }
1153 /**
1154 * Get SureForms Website URL.
1155 *
1156 * @param string $trail The URL trail to append to SureForms website URL. The parameter should not include a leading slash as the base URL already ends with a trailing slash.
1157 * @param array<string, string> $utm_args Optional. An associative array of UTM parameters to append to the URL. Default empty array. Example: [ 'utm_medium' => 'dashboard'].
1158 * @since 0.0.7
1159 * @return string
1160 */
1161 public static function get_sureforms_website_url( $trail, $utm_args = [] ) {
1162 $url = SRFM_WEBSITE;
1163 if ( ! empty( $trail ) && is_string( $trail ) ) {
1164 $url = SRFM_WEBSITE . $trail;
1165 }
1166
1167 if ( ! is_array( $utm_args ) ) {
1168 $utm_args = [];
1169 }
1170
1171 if ( class_exists( 'BSF_UTM_Analytics' ) ) {
1172 $url = \BSF_UTM_Analytics::get_utm_ready_link( $url, 'sureforms', $utm_args );
1173 }
1174
1175 return esc_url( $url );
1176 }
1177
1178 /**
1179 * Validates if the given string is a valid CSS class name.
1180 *
1181 * A valid CSS class name:
1182 * - Does not start with a digit, hyphen, or underscore.
1183 * - Can contain alphanumeric characters, underscores, hyphens, and Unicode letters.
1184 *
1185 * @param string $class_name The class name to validate.
1186 *
1187 * @since 1.3.1
1188 * @return bool True if the class name is valid, otherwise false.
1189 */
1190 public static function is_valid_css_class_name( $class_name ) {
1191 // Regular expression to validate a Unicode-aware CSS class name.
1192 $class_name_regex = '/^[^\d\-_][\w\p{L}\p{N}\-_]*$/u';
1193
1194 // Check if the className matches the pattern.
1195 return preg_match( $class_name_regex, $class_name ) === 1;
1196 }
1197
1198 /**
1199 * Get the gradient css for given gradient parameters.
1200 *
1201 * @param string $type The type of gradient. Default 'linear'.
1202 * @param string $color1 The first color of the gradient. Default '#FFC9B2'.
1203 * @param string $color2 The second color of the gradient. Default '#C7CBFF'.
1204 * @param int $loc1 The location of the first color. Default 0.
1205 * @param int $loc2 The location of the second color. Default 100.
1206 * @param int $angle The angle of the gradient. Default 90.
1207 *
1208 * @since 1.4.4
1209 * @return string The gradient css.
1210 */
1211 public static function get_gradient_css( $type = 'linear', $color1 = '#FFC9B2', $color2 = '#C7CBFF', $loc1 = 0, $loc2 = 100, $angle = 90 ) {
1212 if ( 'linear' === $type ) {
1213 return "linear-gradient({$angle}deg, {$color1} {$loc1}%, {$color2} {$loc2}%)";
1214 }
1215 return "radial-gradient({$color1} {$loc1}%, {$color2} {$loc2}%)";
1216 }
1217
1218 /**
1219 * Return the classes based on background and overlay type to add to the form container.
1220 *
1221 * @param string $background_type The background type.
1222 * @param string $overlay_type The overlay type.
1223 * @param string $bg_image The background image url.
1224 *
1225 * @since 1.4.4
1226 * @return string The classes to add to the form container.
1227 */
1228 public static function get_background_classes( $background_type, $overlay_type, $bg_image = '' ) {
1229 if ( empty( $background_type ) ) {
1230 $background_type = 'color';
1231 }
1232
1233 $background_type_class = '';
1234 $overlay_class = 'image' === $background_type && ! empty( $bg_image ) && $overlay_type ? "srfm-overlay-{$overlay_type}" : '';
1235
1236 // Set the class based on the background type.
1237 switch ( $background_type ) {
1238 case 'image':
1239 $background_type_class = 'srfm-bg-image';
1240 break;
1241 case 'gradient':
1242 $background_type_class = 'srfm-bg-gradient';
1243 break;
1244 default:
1245 $background_type_class = 'srfm-bg-color';
1246 break;
1247 }
1248
1249 return self::join_strings( [ $background_type_class, $overlay_class ] );
1250 }
1251 }
1252