PluginProbe
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz / 1.7.3
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz v1.7.3
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,529 lines 54.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Sureforms Submit Class file.
4 *
5 * @package sureforms.
6 * @since 0.0.1
7 */
8
9 namespace SRFM\Inc;
10
11 use SRFM\Inc\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' => [ self::class, 'sanitize_textarea' ],
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-address-label-font-size' => '14px',
733 '--srfm-address-label-line-height' => '20px',
734 '--srfm-address-description-font-size' => '12px',
735 '--srfm-address-description-line-height' => '16px',
736 '--srfm-col-gap-between-fields' => '12px',
737 '--srfm-row-gap-between-fields' => '12px',
738 '--srfm-gap-below-address-label' => '12px',
739 // Dropdown Variables.
740 '--srfm-dropdown-font-size' => '14px',
741 '--srfm-dropdown-gap-between-input-menu' => '4px',
742 '--srfm-dropdown-badge-padding' => '2px 6px',
743 '--srfm-dropdown-multiselect-font-size' => '12px',
744 '--srfm-dropdown-multiselect-line-height' => '16px',
745 '--srfm-dropdown-padding-right' => '12px',
746 // initial padding and from 20px - 12px for dropdown arrow width and 8px for gap before dropdown arrow.
747 '--srfm-dropdown-padding-right-icon' => 'calc( var( --srfm-dropdown-padding-right ) + 20px )',
748 '--srfm-dropdown-multiselect-padding' => '8px var( --srfm-dropdown-padding-right-icon ) 8px 8px',
749 // Input Field Variables.
750 '--srfm-input-height' => '40px',
751 '--srfm-input-field-padding' => '10px 12px',
752 '--srfm-input-field-font-size' => '14px',
753 '--srfm-input-field-line-height' => '20px',
754 '--srfm-input-field-margin-top' => '4px',
755 '--srfm-input-field-margin-bottom' => '4px',
756 // Checkbox and GDPR Variables.
757 '--srfm-checkbox-label-font-size' => '14px',
758 '--srfm-checkbox-label-line-height' => '20px',
759 '--srfm-checkbox-description-font-size' => '12px',
760 '--srfm-checkbox-description-line-height' => '16px',
761 '--srfm-check-ctn-width' => '16px',
762 '--srfm-check-ctn-height' => '16px',
763 '--srfm-check-svg-size' => '10px',
764 '--srfm-checkbox-margin-top-frontend' => '2px',
765 '--srfm-checkbox-margin-top-editor' => '3px',
766 '--srfm-check-gap' => '8px',
767 '--srfm-checkbox-description-margin-left' => '24px',
768 // Phone Number field variables.
769 '--srfm-flag-section-padding' => '10px 0 10px 12px',
770 '--srfm-gap-between-icon-text' => '8px',
771 // Label Variables.
772 '--srfm-label-font-size' => '14px',
773 '--srfm-label-line-height' => '20px',
774 // Description Variables.
775 '--srfm-description-font-size' => '12px',
776 '--srfm-description-line-height' => '16px',
777 // Button Variables.
778 '--srfm-btn-padding' => '8px 14px',
779 '--srfm-btn-font-size' => '14px',
780 '--srfm-btn-line-height' => '20px',
781 // Multi Choice Variables.
782 '--srfm-multi-choice-horizontal-padding' => '16px',
783 '--srfm-multi-choice-vertical-padding' => '16px',
784 '--srfm-multi-choice-internal-option-gap' => '8px',
785 '--srfm-multi-choice-vertical-svg-size' => '32px',
786 '--srfm-multi-choice-horizontal-image-size' => '20px',
787 '--srfm-multi-choice-vertical-image-size' => '100px',
788 '--srfm-multi-choice-outer-padding' => '0',
789 ],
790 'medium' => [
791 '--srfm-row-gap-between-blocks' => '18px',
792 // Address block gap and spacing variables.
793 '--srfm-address-label-font-size' => '16px',
794 '--srfm-address-label-line-height' => '24px',
795 '--srfm-address-description-font-size' => '14px',
796 '--srfm-address-description-line-height' => '20px',
797 '--srfm-col-gap-between-fields' => '16px',
798 '--srfm-row-gap-between-fields' => '16px',
799 '--srfm-gap-below-address-label' => '14px',
800 // Input Field Variables.
801 '--srfm-input-height' => '44px',
802 '--srfm-input-field-font-size' => '16px',
803 '--srfm-input-field-line-height' => '24px',
804 '--srfm-input-field-margin-top' => '6px',
805 '--srfm-input-field-margin-bottom' => '6px',
806 // Checkbox and GDPR Variables.
807 '--srfm-checkbox-label-font-size' => '16px',
808 '--srfm-checkbox-label-line-height' => '24px',
809 '--srfm-checkbox-description-font-size' => '14px',
810 '--srfm-checkbox-description-line-height' => '20px',
811 '--srfm-checkbox-margin-top-frontend' => '4px',
812 '--srfm-checkbox-margin-top-editor' => '6px',
813 '--srfm-checkbox-description-margin-left' => '24px',
814 // Label Variables.
815 '--srfm-label-font-size' => '16px',
816 '--srfm-label-line-height' => '24px',
817 // Description Variables.
818 '--srfm-description-font-size' => '14px',
819 '--srfm-description-line-height' => '20px',
820 // Button Variables.
821 '--srfm-btn-padding' => '10px 14px',
822 '--srfm-btn-font-size' => '16px',
823 '--srfm-btn-line-height' => '24px',
824 // Multi Choice Variables.
825 '--srfm-multi-choice-horizontal-padding' => '20px',
826 '--srfm-multi-choice-vertical-padding' => '20px',
827 '--srfm-multi-choice-vertical-svg-size' => '40px',
828 '--srfm-multi-choice-horizontal-image-size' => '24px',
829 '--srfm-multi-choice-vertical-image-size' => '120px',
830 '--srfm-multi-choice-outer-padding' => '2px',
831 ],
832 'large' => [
833 '--srfm-row-gap-between-blocks' => '20px',
834 // Address Block Gap and Spacing Variables.
835 '--srfm-address-label-font-size' => '18px',
836 '--srfm-address-label-line-height' => '28px',
837 '--srfm-address-description-font-size' => '16px',
838 '--srfm-address-description-line-height' => '24px',
839 '--srfm-col-gap-between-fields' => '16px',
840 '--srfm-row-gap-between-fields' => '20px',
841 '--srfm-gap-below-address-label' => '16px',
842 // Dropdown Variables.
843 '--srfm-dropdown-font-size' => '16px',
844 '--srfm-dropdown-gap-between-input-menu' => '6px',
845 '--srfm-dropdown-badge-padding' => '6px 6px',
846 '--srfm-dropdown-multiselect-font-size' => '14px',
847 '--srfm-dropdown-multiselect-line-height' => '20px',
848 '--srfm-dropdown-padding-right' => '14px',
849 // Input Field Variables.
850 '--srfm-input-height' => '48px',
851 '--srfm-input-field-padding' => '10px 14px',
852 '--srfm-input-field-font-size' => '18px',
853 '--srfm-input-field-line-height' => '28px',
854 '--srfm-input-field-margin-top' => '8px',
855 '--srfm-input-field-margin-bottom' => '8px',
856 // Checkbox and GDPR Variables.
857 '--srfm-checkbox-label-font-size' => '18px',
858 '--srfm-checkbox-label-line-height' => '28px',
859 '--srfm-checkbox-description-font-size' => '16px',
860 '--srfm-checkbox-description-line-height' => '24px',
861 '--srfm-check-ctn-width' => '20px',
862 '--srfm-check-ctn-height' => '20px',
863 '--srfm-check-svg-size' => '14px',
864 '--srfm-check-gap' => '10px',
865 '--srfm-checkbox-margin-top-frontend' => '4px',
866 '--srfm-checkbox-margin-top-editor' => '5px',
867 '--srfm-checkbox-description-margin-left' => '30px',
868 // Label Variables.
869 '--srfm-label-font-size' => '18px',
870 '--srfm-label-line-height' => '28px',
871 // Description Variables.
872 '--srfm-description-font-size' => '16px',
873 '--srfm-description-line-height' => '24px',
874 // Button Variables.
875 '--srfm-btn-padding' => '10px 14px',
876 '--srfm-btn-font-size' => '18px',
877 '--srfm-btn-line-height' => '28px',
878 // Multi Choice Variables.
879 '--srfm-multi-choice-horizontal-padding' => '24px',
880 '--srfm-multi-choice-vertical-padding' => '24px',
881 '--srfm-multi-choice-internal-option-gap' => '12px',
882 '--srfm-multi-choice-vertical-svg-size' => '48px',
883 '--srfm-multi-choice-horizontal-image-size' => '28px',
884 '--srfm-multi-choice-vertical-image-size' => '140px',
885 '--srfm-multi-choice-outer-padding' => '4px',
886 ],
887 ]
888 );
889 // Return complete sizes array if field_spacing is false. Required in case of JS for Editor changes.
890 if ( ! $field_spacing ) {
891 return $sizes;
892 }
893
894 $selected_size = $sizes['small'];
895 if ( 'small' !== $field_spacing && isset( $sizes[ $field_spacing ] ) ) {
896 $selected_size = array_merge( $selected_size, $sizes[ $field_spacing ] );
897 }
898
899 return $selected_size;
900 }
901
902 /**
903 * Array of SureForms blocks which get have user input.
904 *
905 * @since 0.0.10
906 * @return array<string>
907 */
908 public static function get_sureforms_blocks() {
909 return apply_filters(
910 'srfm_blocks',
911 [
912 'srfm/input',
913 'srfm/email',
914 'srfm/textarea',
915 'srfm/number',
916 'srfm/checkbox',
917 'srfm/gdpr',
918 'srfm/phone',
919 'srfm/address',
920 'srfm/dropdown',
921 'srfm/multi-choice',
922 'srfm/radio',
923 'srfm/submit',
924 'srfm/url',
925 ]
926 );
927 }
928
929 /**
930 * Render a site key missing error message.
931 *
932 * @param string $provider_name Name of the captcha provider (e.g., HCaptcha, Google reCAPTCHA, Turnstile).
933 * @since 1.7.0
934 * @since 1.7.1 moved to inc/helper.php from inc/generate-form-markup.php
935 * @return void
936 */
937 public static function render_missing_sitekey_error( $provider_name ) {
938 $icon = self::fetch_svg( 'info_circle', '', 'aria-hidden="true"' );
939 ?>
940 <p id="sitekey-error" class="srfm-common-error-message srfm-error-message" hidden="false">
941 <?php echo wp_kses( $icon, self::$allowed_tags_svg ); ?>
942 <span class="srfm-error-content">
943 <?php
944 echo esc_html(
945 sprintf(
946 /* translators: %s: Provider name like HCaptcha, Google reCAPTCHA, Turnstile */
947 __( '%s sitekey is missing. Please contact your site administrator.', 'sureforms' ),
948 $provider_name
949 )
950 );
951 ?>
952 </span>
953 </p>
954 <?php
955 }
956
957 /**
958 * Process blocks and inner blocks.
959 *
960 * @param array<mixed> $blocks The block data.
961 * @param array<string> $slugs The array of existing slugs.
962 * @param bool $updated The array of existing slugs.
963 * @param string $prefix The array of existing slugs.
964 * @param bool $skip_checking_existing_slug Skips the checking of existing slug if passed true. More information documented inside this function.
965 * @since 0.0.10
966 * @return array
967 */
968 public static function process_blocks( $blocks, &$slugs, &$updated, $prefix = '', $skip_checking_existing_slug = false ) {
969
970 if ( ! is_array( $blocks ) ) {
971 return [ $blocks, $slugs, $updated ];
972 }
973
974 foreach ( $blocks as $index => $block ) {
975
976 if ( ! is_array( $block ) ) {
977 continue;
978 }
979 // Checking only for SureForms blocks which can have user input.
980 if ( empty( $block['blockName'] ) || ! in_array( $block['blockName'], self::get_sureforms_blocks(), true ) ) {
981 continue;
982 }
983
984 /**
985 * Lets continue if slug already exists.
986 * This will ensure that we don't update already existing slugs.
987 */
988 if ( isset( $block['attrs'] ) && ! empty( $block['attrs']['slug'] ) && ! in_array( $block['attrs']['slug'], $slugs, true ) ) {
989
990 // Made it associative array, so that we can directly check it using block_id rather than mapping or using "in_array" for the checks.
991 $slugs[ $block['attrs']['block_id'] ] = self::get_string_value( $block['attrs']['slug'] );
992 continue;
993 }
994
995 if ( $skip_checking_existing_slug && empty( $block['innerBlocks'] ) && isset( $slugs[ $block['attrs']['block_id'] ] ) ) {
996 /**
997 * Skip re-processing of the already process or existing slugs if above parameter "$skip_checking_existing_slug" is passed as true.
998 * This is helpful in the scenarios where we need to compare and verify between already saved blocks and new unsaved blocks parsed
999 * from the contents.
1000 *
1001 * However, it is also necessary to make sure if that current block is not a parent / wrapper block
1002 * by checking "$block['innerBlocks']" empty.
1003 *
1004 * And finally, checking if the block-id "$block['attrs']['block_id']" is already set in the list of "$slugs",
1005 * making sure that we are only processing the new blocks.
1006 */
1007 continue;
1008 }
1009
1010 if ( is_array( $blocks[ $index ]['attrs'] ) ) {
1011
1012 $blocks[ $index ]['attrs']['slug'] = self::generate_unique_block_slug( $block, $slugs, $prefix );
1013 $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.
1014 $updated = true;
1015 if ( is_array( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) ) {
1016
1017 [ $blocks[ $index ]['innerBlocks'], $slugs, $updated ] = self::process_blocks( $block['innerBlocks'], $slugs, $updated, $blocks[ $index ]['attrs']['slug'] );
1018
1019 }
1020 }
1021 }
1022 return [ $blocks, $slugs, $updated ];
1023 }
1024
1025 /**
1026 * Generates slug based on the provided block and existing slugs.
1027 *
1028 * @param array<mixed> $block The block data.
1029 * @param array<string> $slugs The array of existing slugs.
1030 * @param string $prefix The array of existing slugs.
1031 * @since 0.0.10
1032 * @return string The generated unique block slug.
1033 */
1034 public static function generate_unique_block_slug( $block, $slugs, $prefix ) {
1035 $slug = is_string( $block['blockName'] ) ? $block['blockName'] : '';
1036
1037 if ( ! empty( $block['attrs']['label'] ) && is_string( $block['attrs']['label'] ) ) {
1038 $slug = sanitize_title( $block['attrs']['label'] );
1039 }
1040
1041 if ( ! empty( $prefix ) ) {
1042 $slug = $prefix . '-' . $slug;
1043 }
1044
1045 return self::generate_slug( $slug, $slugs );
1046 }
1047
1048 /**
1049 * This function ensures that the slug is unique.
1050 * If the slug is already taken, it appends a number to the slug to make it unique.
1051 *
1052 * @param string $slug test to be converted to slug.
1053 * @param array<string> $slugs An array of existing slugs.
1054 * @since 0.0.10
1055 * @return string The unique slug.
1056 */
1057 public static function generate_slug( $slug, $slugs ) {
1058 $slug = sanitize_title( $slug );
1059
1060 if ( ! in_array( $slug, $slugs, true ) ) {
1061 return $slug;
1062 }
1063
1064 $index = 1;
1065
1066 while ( in_array( $slug . '-' . $index, $slugs, true ) ) {
1067 $index++;
1068 }
1069
1070 return $slug . '-' . $index;
1071 }
1072
1073 /**
1074 * Encode data to JSON. This function will encode the data with JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE.
1075 *
1076 * @since 0.0.11
1077 * @param array<mixed> $data The data to encode.
1078 * @return string|false The JSON representation of the value on success or false on failure.
1079 */
1080 public static function encode_json( $data ) {
1081 return wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
1082 }
1083
1084 /**
1085 * Returns true if SureTriggers plugin is ready for the custom app.
1086 *
1087 * @since 1.0.3
1088 * @return bool Returns true if SureTriggers plugin is ready for the custom app.
1089 */
1090 public static function is_suretriggers_ready() {
1091 if ( ! defined( 'SURE_TRIGGERS_FILE' ) ) {
1092 // Probably plugin is de-activated or not installed at all.
1093 return false;
1094 }
1095
1096 $suretriggers_data = get_option( 'suretrigger_options', [] );
1097 if ( ! is_array( $suretriggers_data ) || empty( $suretriggers_data['secret_key'] ) || ! is_string( $suretriggers_data['secret_key'] ) ) {
1098 // SureTriggers is not authenticated yet.
1099 return false;
1100 }
1101
1102 return true;
1103 }
1104
1105 /**
1106 * Registers script translations for a specific handle.
1107 *
1108 * This function sets the script translations for a given script handle, allowing
1109 * localization of JavaScript strings using the specified text domain and path.
1110 *
1111 * @param string $handle The script handle to apply translations to.
1112 * @param string $domain Optional. The text domain for translations. Default is 'sureforms'.
1113 * @param string $path Optional. The path to the translation files. Default is the 'languages' folder in the SureForms directory.
1114 *
1115 * @since 1.0.5
1116 * @return void
1117 */
1118 public static function register_script_translations( $handle, $domain = 'sureforms', $path = SRFM_DIR . 'languages' ) {
1119 wp_set_script_translations( $handle, $domain, $path );
1120 }
1121
1122 /**
1123 * Validates whether the specified conditions or a single key-value pair exist in the request context.
1124 *
1125 * - If `$conditions` is provided as an array, it will validate all key-value pairs in `$conditions`
1126 * against the `$_REQUEST` superglobal.
1127 * - If `$conditions` is empty, it validates a single key-value pair from `$key` and `$value`.
1128 *
1129 * @param string $value The expected value to match in the request if `$conditions` is not used.
1130 * @param string $key The key to check for in the request if `$conditions` is not used.
1131 * @param array<string, string> $conditions An optional associative array of key-value pairs to validate.
1132 * @since 1.1.1
1133 * @return bool Returns true if all conditions are met or the single key-value pair is valid, otherwise false.
1134 */
1135 public static function validate_request_context( $value, $key = 'post_type', array $conditions = [] ) {
1136 // If conditions are provided, validate all key-value pairs in the conditions array.
1137 if ( ! empty( $conditions ) ) {
1138 foreach ( $conditions as $condition_key => $condition_value ) {
1139 if ( ! isset( $_REQUEST[ $condition_key ] ) || $_REQUEST[ $condition_key ] !== $condition_value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a controlled comparison of request values.
1140 // Return false if any condition is not satisfied.
1141 return false;
1142 }
1143 }
1144 // Return true if all conditions are satisfied.
1145 return true;
1146 }
1147
1148 // Validate $value and $key when no conditions are provided.
1149 if ( empty( $key ) || empty( $value ) ) {
1150 return false;
1151 }
1152
1153 // Validate a single key-value pair when no conditions are provided.
1154 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.
1155 }
1156
1157 /**
1158 * Retrieve the list of excluded fields for form data processing.
1159 *
1160 * This method returns an array of field keys that should be excluded when
1161 * processing form data.
1162 *
1163 * @since 1.1.1
1164 * @return array<string> Returns the string array of excluded fields.
1165 */
1166 public static function get_excluded_fields() {
1167 $excluded_fields = [ 'srfm-honeypot-field', 'g-recaptcha-response', 'srfm-sender-email-field', 'form-id' ];
1168
1169 return apply_filters( 'srfm_excluded_fields', $excluded_fields );
1170 }
1171
1172 /**
1173 * Check whether the current page is a SureForms admin page.
1174 *
1175 * @since 1.2.2
1176 * @return bool Returns true if the current page is a SureForms admin page, otherwise false.
1177 */
1178 public static function is_sureforms_admin_page() {
1179 $current_screen = get_current_screen();
1180 $is_screen_sureforms_menu = self::validate_request_context( 'sureforms_menu', 'page' );
1181 $is_screen_add_new_form = self::validate_request_context( 'add-new-form', 'page' );
1182 $is_screen_sureforms_form_settings = self::validate_request_context( 'sureforms_form_settings', 'page' );
1183 $is_screen_sureforms_entries = self::validate_request_context( SRFM_ENTRIES, 'page' );
1184 $is_post_type_sureforms_form = $current_screen && SRFM_FORMS_POST_TYPE === $current_screen->post_type;
1185
1186 return $is_screen_sureforms_menu || $is_screen_add_new_form || $is_screen_sureforms_form_settings || $is_screen_sureforms_entries || $is_post_type_sureforms_form;
1187 }
1188
1189 /**
1190 * Filters and concatenates valid class names from an array.
1191 *
1192 * @param array<string> $class_names The array containing potential class names.
1193 * @since 1.4.0
1194 * @return string The concatenated string of valid class names separated by spaces.
1195 */
1196 public static function join_strings( $class_names ) {
1197 // Filter the array to include only valid class names.
1198 $valid_class_names = array_filter(
1199 $class_names,
1200 static function ( $value ) {
1201 return is_string( $value ) && '' !== $value && false !== $value;
1202 }
1203 );
1204
1205 // Concatenate the valid class names with spaces and return.
1206 return implode( ' ', $valid_class_names );
1207 }
1208 /**
1209 * Get SureForms Website URL.
1210 *
1211 * @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.
1212 * @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'].
1213 * @since 0.0.7
1214 * @return string
1215 */
1216 public static function get_sureforms_website_url( $trail, $utm_args = [] ) {
1217 $url = SRFM_WEBSITE;
1218 if ( ! empty( $trail ) && is_string( $trail ) ) {
1219 $url = SRFM_WEBSITE . $trail;
1220 }
1221
1222 if ( ! is_array( $utm_args ) ) {
1223 $utm_args = [];
1224 }
1225
1226 if ( class_exists( 'BSF_UTM_Analytics' ) ) {
1227 $url = \BSF_UTM_Analytics::get_utm_ready_link( $url, 'sureforms', $utm_args );
1228 }
1229
1230 return esc_url( $url );
1231 }
1232
1233 /**
1234 * Validates if the given string is a valid CSS class name.
1235 *
1236 * A valid CSS class name:
1237 * - Does not start with a digit, hyphen, or underscore.
1238 * - Can contain alphanumeric characters, underscores, hyphens, and Unicode letters.
1239 *
1240 * @param string $class_name The class name to validate.
1241 *
1242 * @since 1.3.1
1243 * @return bool True if the class name is valid, otherwise false.
1244 */
1245 public static function is_valid_css_class_name( $class_name ) {
1246 // Regular expression to validate a Unicode-aware CSS class name.
1247 $class_name_regex = '/^[^\d\-_][\w\p{L}\p{N}\-_]*$/u';
1248
1249 // Check if the className matches the pattern.
1250 return preg_match( $class_name_regex, $class_name ) === 1;
1251 }
1252
1253 /**
1254 * Get the gradient css for given gradient parameters.
1255 *
1256 * @param string $type The type of gradient. Default 'linear'.
1257 * @param string $color1 The first color of the gradient. Default '#FFC9B2'.
1258 * @param string $color2 The second color of the gradient. Default '#C7CBFF'.
1259 * @param int $loc1 The location of the first color. Default 0.
1260 * @param int $loc2 The location of the second color. Default 100.
1261 * @param int $angle The angle of the gradient. Default 90.
1262 *
1263 * @since 1.4.4
1264 * @return string The gradient css.
1265 */
1266 public static function get_gradient_css( $type = 'linear', $color1 = '#FFC9B2', $color2 = '#C7CBFF', $loc1 = 0, $loc2 = 100, $angle = 90 ) {
1267 if ( 'linear' === $type ) {
1268 return "linear-gradient({$angle}deg, {$color1} {$loc1}%, {$color2} {$loc2}%)";
1269 }
1270 return "radial-gradient({$color1} {$loc1}%, {$color2} {$loc2}%)";
1271 }
1272
1273 /**
1274 * Return the classes based on background and overlay type to add to the form container.
1275 *
1276 * @param string $background_type The background type.
1277 * @param string $overlay_type The overlay type.
1278 * @param string $bg_image The background image url.
1279 *
1280 * @since 1.4.4
1281 * @return string The classes to add to the form container.
1282 */
1283 public static function get_background_classes( $background_type, $overlay_type, $bg_image = '' ) {
1284 if ( empty( $background_type ) ) {
1285 $background_type = 'color';
1286 }
1287
1288 $background_type_class = '';
1289 $overlay_class = 'image' === $background_type && ! empty( $bg_image ) && $overlay_type ? "srfm-overlay-{$overlay_type}" : '';
1290
1291 // Set the class based on the background type.
1292 switch ( $background_type ) {
1293 case 'image':
1294 $background_type_class = 'srfm-bg-image';
1295 break;
1296 case 'gradient':
1297 $background_type_class = 'srfm-bg-gradient';
1298 break;
1299 default:
1300 $background_type_class = 'srfm-bg-color';
1301 break;
1302 }
1303
1304 return self::join_strings( [ $background_type_class, $overlay_class ] );
1305 }
1306
1307 /**
1308 * Custom escape function for the textarea with rich text support.
1309 *
1310 * @param string $content The content submitted by the user in the textarea block.
1311 * @since 1.7.1
1312 *
1313 * @return string Escaped content.
1314 */
1315 public static function esc_textarea( $content ) {
1316 $content = wpautop( self::sanitize_textarea( $content ) );
1317
1318 return trim( str_replace( [ "\r\n", "\r", "\n" ], '', $content ) );
1319 }
1320
1321 /**
1322 * Custom sanitization function for the textarea with rich text support.
1323 *
1324 * @param string $content The content submitted by the user in the textarea block.
1325 * @since 1.7.1
1326 *
1327 * @return string Sanitized content.
1328 */
1329 public static function sanitize_textarea( $content ) {
1330 $count = 1;
1331 $content = convert_invalid_entities( $content );
1332
1333 // Remove the 'script' and 'style' tags recursively from the content.
1334 while ( $count ) {
1335 $content = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', self::get_string_value( $content ), - 1, $count );
1336 }
1337
1338 // Disable the safe style attribute parsing for the textarea block.
1339 add_filter( 'safe_style_css', [ self::class, 'disable_style_attr_parsing' ], 10, 1 );
1340 $content = wp_kses_post( self::get_string_value( $content ) );
1341
1342 // Remove the filter after sanitization to avoid affecting other blocks.
1343 remove_filter( 'safe_style_css', [ self::class, 'disable_style_attr_parsing' ], 10 );
1344
1345 // Ensure all tags are balanced.
1346 return force_balance_tags( $content );
1347 }
1348
1349 /**
1350 * Disable parsing of style attributes for the textarea block.
1351 *
1352 * @param array<string> $allowed_styles The allowed styles.
1353 * @since 1.7.1
1354 *
1355 * @return array An empty array to disable style attribute parsing.
1356 */
1357 public static function disable_style_attr_parsing( $allowed_styles ) {
1358 unset( $allowed_styles );
1359 // Disable parsing of style attributes.
1360 return [];
1361 }
1362 /**
1363 * Strips JavaScript attributes from HTML content.
1364 *
1365 * @param string $html The HTML content to process.
1366 * @since 1.7.1
1367 * @return string The cleaned HTML content without JavaScript attributes.
1368 */
1369 public static function strip_js_attributes( $html ) {
1370 $dom = new \DOMDocument();
1371
1372 // Suppress warnings due to malformed HTML.
1373 libxml_use_internal_errors( true );
1374 $loaded = $dom->loadHTML( '<?xml encoding="utf-8" ?>' . $html );
1375 libxml_clear_errors();
1376
1377 if ( ! $loaded ) {
1378 return $html; // Return original HTML if loading fails.
1379 }
1380
1381 $xpath = new \DOMXPath( $dom );
1382
1383 // 1. Remove all <script> tags.
1384 $script_nodes = $xpath->query( '//script' );
1385 if ( $script_nodes instanceof \DOMNodeList ) {
1386 foreach ( $script_nodes as $script ) {
1387 // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- This is a DOM element.
1388 $parent_node = $script->parentNode;
1389 if ( $parent_node instanceof \DOMNode ) {
1390 $parent_node->removeChild( $script );
1391 }
1392 }
1393 }
1394
1395 // 2. Remove all attributes that start with "on" (like onclick, onmouseover, etc.).
1396 $elements_with_on_attrs = $xpath->query( '//*[@*[starts-with(name(), "on")]]' );
1397 if ( $elements_with_on_attrs instanceof \DOMNodeList ) {
1398 foreach ( $elements_with_on_attrs as $element ) {
1399 if ( $element instanceof \DOMElement && $element->hasAttributes() ) {
1400 foreach ( iterator_to_array( $element->attributes ) as $attr ) {
1401 if ( $attr instanceof \DOMAttr && stripos( $attr->name, 'on' ) === 0 ) {
1402 $element->removeAttribute( $attr->name );
1403 }
1404 }
1405 }
1406 }
1407 }
1408
1409 // Return cleaned HTML.
1410 $body = $dom->getElementsByTagName( 'body' )->item( 0 );
1411 if ( $body instanceof \DOMNode ) {
1412 $cleaned_html = $dom->saveHTML( $body );
1413 return is_string( $cleaned_html ) ? $cleaned_html : '';
1414 }
1415 return '';
1416 }
1417
1418 /**
1419 * Encodes the given string with base64.
1420 * Moved from admin class to here.
1421 *
1422 * @param string $logo contains svg's.
1423 * @return string
1424 */
1425 public static function encode_svg( $logo ) {
1426 return 'data:image/svg+xml;base64,' . base64_encode( $logo ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1427 }
1428
1429 /**
1430 * Get plugin status
1431 *
1432 * @since 0.0.1
1433 * @since 1.7.0 moved to inc/helper.php from inc/admin-ajax.php
1434 *
1435 * @param string $plugin_init_file Plugin init file.
1436 * @return string
1437 */
1438 public static function get_plugin_status( $plugin_init_file ) {
1439
1440 $installed_plugins = get_plugins();
1441
1442 if ( ! isset( $installed_plugins[ $plugin_init_file ] ) ) {
1443 return 'Install';
1444 }
1445 if ( is_plugin_active( $plugin_init_file ) ) {
1446 return 'Activated';
1447 }
1448 return 'Installed';
1449 }
1450
1451 /**
1452 * Check if the starter template premium plugin is installed and return its file path.
1453 *
1454 * @since 1.7.3
1455 *
1456 * @return string The plugin file path if premium is installed, otherwise the default starter sites plugin file path.
1457 */
1458 public static function check_starter_template_plugin() {
1459 if ( ! function_exists( 'get_plugins' ) ) {
1460 require_once ABSPATH . 'wp-admin/includes/plugin.php';
1461 }
1462 $plugins = get_plugins();
1463
1464 $premium = 'astra-pro-sites/astra-pro-sites.php';
1465
1466 return isset( $plugins[ $premium ] ) ? $premium : 'astra-sites/astra-sites.php';
1467 }
1468
1469 /**
1470 * Get sureforms recommended integrations.
1471 *
1472 * @since 0.0.1
1473 * @since 1.7.0 moved to inc/helper.php from inc/admin-ajax.php
1474 *
1475 * @return array<mixed>
1476 */
1477 public static function sureforms_get_integration() {
1478 $suretrigger_connected = apply_filters( 'suretriggers_is_user_connected', '' );
1479 $logo_sure_triggers = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suretriggers.svg' );
1480 $logo_full = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suretriggers_full.svg' );
1481 $logo_sure_mails = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suremails.svg' );
1482 $logo_sure_cart = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/surecart.svg' );
1483 $logo_starter_templates = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/starterTemplates.svg' );
1484 return apply_filters(
1485 'srfm_integrated_plugins',
1486 [
1487 'sure_triggers' => [
1488 'title' => __( 'OttoKit', 'sureforms' ),
1489 'subtitle' => __( 'No-code automation tool for WordPress.', 'sureforms' ),
1490 'description' => __( 'OttoKit is a powerful automation platform that helps you connect your various plugins and apps together. It allows you to automate repetitive tasks, so you can focus on more important work.', 'sureforms' ),
1491 'status' => self::get_plugin_status( 'suretriggers/suretriggers.php' ),
1492 'slug' => 'suretriggers',
1493 'path' => 'suretriggers/suretriggers.php',
1494 'redirection' => admin_url( 'admin.php?page=suretriggers' ),
1495 'logo' => self::encode_svg( is_string( $logo_sure_triggers ) ? $logo_sure_triggers : '' ),
1496 'logo_full' => self::encode_svg( is_string( $logo_full ) ? $logo_full : '' ),
1497 'connected' => $suretrigger_connected,
1498 ],
1499 'sure_mails' => [
1500 'title' => __( 'SureMail', 'sureforms' ),
1501 'subtitle' => __( 'Free and easy SMTP mails plugin.', 'sureforms' ),
1502 'status' => self::get_plugin_status( 'suremails/suremails.php' ),
1503 'slug' => 'suremails',
1504 'path' => 'suremails/suremails.php',
1505 'redirection' => admin_url( 'options-general.php?page=suremail#/dashboard' ),
1506 'logo' => self::encode_svg( is_string( $logo_sure_mails ) ? $logo_sure_mails : '' ),
1507 ],
1508 'sure_cart' => [
1509 'title' => __( 'SureCart', 'sureforms' ),
1510 'subtitle' => __( 'The new way to sell on WordPress.', 'sureforms' ),
1511 'status' => self::get_plugin_status( 'surecart/surecart.php' ),
1512 'slug' => 'surecart',
1513 'path' => 'surecart/surecart.php',
1514 'logo' => self::encode_svg( is_string( $logo_sure_cart ) ? $logo_sure_cart : '' ),
1515 ],
1516 'starter_templates' => [
1517 'title' => __( 'Starter Templates', 'sureforms' ),
1518 'subtitle' => __( 'Build your dream website in minutes with AI.', 'sureforms' ),
1519 'status' => self::get_plugin_status( self::check_starter_template_plugin() ),
1520 'slug' => 'astra-sites',
1521 'path' => self::check_starter_template_plugin(),
1522 'redirection' => admin_url( 'admin.php?page=starter-templates' ),
1523 'logo' => self::encode_svg( is_string( $logo_starter_templates ) ? $logo_starter_templates : '' ),
1524 ],
1525 ]
1526 );
1527 }
1528 }
1529