PluginProbe
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz / 2.7.0
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz v2.7.0
2.12.6 2.12.5 2.12.4 2.12.3 2.12.2 2.12.1 2.12.0 2.11.1 2.11.0 2.10.1 2.10.0 2.9.1 2.9.0 2.8.2 2.8.1 2.7.0 2.7.1 2.8.0 trunk 0.0.10 0.0.11 0.0.12 0.0.13 0.0.2 0.0.3 All 96 releases
sureforms / inc / helper.php
helper.php
2,304 lines 78.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
16 if ( ! defined( 'ABSPATH' ) ) {
17 exit; // Exit if accessed directly.
18 }
19
20 /**
21 * Sureforms Helper Class.
22 *
23 * @since 0.0.1
24 */
25 class Helper {
26 use Get_Instance;
27
28 /**
29 * Allowed HTML tags for SVG.
30 *
31 * @var array<string, array<string, bool>>
32 */
33 public static $allowed_tags_svg = [
34 'span' => [
35 'class' => true,
36 'aria-hidden' => true,
37 ],
38 'svg' => [
39 'xmlns' => true,
40 'width' => true,
41 'height' => true,
42 'viewBox' => true,
43 'fill' => true,
44 ],
45 'path' => [
46 'd' => true,
47 'stroke' => true,
48 'stroke-opacity' => true,
49 'stroke-width' => true,
50 'stroke-linecap' => true,
51 'stroke-linejoin' => true,
52 ],
53 ];
54
55 /**
56 * Sureforms SVGs.
57 *
58 * @var mixed srfm_svgs
59 */
60 private static $srfm_svgs = null;
61
62 /**
63 * Get common error message.
64 *
65 * @since 0.0.2
66 * @return array<string>
67 */
68 public static function get_common_err_msg() {
69 return [
70 'required' => __( 'This field is required.', 'sureforms' ),
71 'unique' => __( 'Value needs to be unique.', 'sureforms' ),
72 ];
73 }
74
75 /**
76 * Convert a file URL to a file path.
77 *
78 * @param string $file_url The URL of the file.
79 *
80 * @since 1.3.0
81 * @return string The file path.
82 */
83 public static function convert_fileurl_to_filepath( $file_url ) {
84 static $upload_dir = null;
85 if ( ! $upload_dir ) {
86 // Internally cache the upload directory.
87 $upload_dir = wp_get_upload_dir();
88 }
89 return wp_normalize_path( str_replace( $upload_dir['baseurl'], $upload_dir['basedir'], $file_url ) );
90 }
91
92 /**
93 * Checks if current value is string or else returns default value
94 *
95 * @param mixed $data data which need to be checked if is string.
96 *
97 * @since 0.0.1
98 * @return string
99 */
100 public static function get_string_value( $data ) {
101 if ( is_scalar( $data ) ) {
102 return (string) $data;
103 }
104 if ( is_object( $data ) && method_exists( $data, '__toString' ) ) {
105 return $data->__toString();
106 }
107 if ( is_null( $data ) ) {
108 return '';
109 }
110 return '';
111 }
112 /**
113 * Checks if current value is number or else returns default value
114 *
115 * @param mixed $value data which need to be checked if is string.
116 * @param int $base value can be set is $data is not a string, defaults to empty string.
117 *
118 * @since 0.0.1
119 * @return int
120 */
121 public static function get_integer_value( $value, $base = 10 ) {
122 if ( is_numeric( $value ) ) {
123 return (int) $value;
124 }
125 if ( is_string( $value ) ) {
126 $trimmed_value = trim( $value );
127 return intval( $trimmed_value, $base );
128 }
129 return 0;
130 }
131
132 /**
133 * Validate a date string in Y-m-d format.
134 *
135 * @param string $date The date string to validate.
136 * @since 2.6.0
137 * @return bool
138 */
139 public static function validate_date( string $date ): bool {
140 $d = \DateTime::createFromFormat( 'Y-m-d', $date );
141 return $d && $d->format( 'Y-m-d' ) === $date;
142 }
143
144 /**
145 * Returns a boolean representation of the given value.
146 *
147 * @param mixed $data Data which needs to be converted to boolean.
148 *
149 * @since 2.5.2
150 * @return bool
151 */
152 public static function get_boolean_value( $data ) {
153 return (bool) $data;
154 }
155
156 /**
157 * Checks if current value is an array or else returns default value
158 *
159 * @param mixed $data Data which needs to be checked if it is an array.
160 *
161 * @since 0.0.3
162 * @return array
163 */
164 public static function get_array_value( $data ) {
165 if ( is_array( $data ) ) {
166 return $data;
167 }
168 if ( is_null( $data ) ) {
169 return [];
170 }
171 return (array) $data;
172 }
173
174 /**
175 * Extracts the field type from the dynamic field key ( or field slug ).
176 *
177 * @param string $field_key Dynamic field key.
178 * @since 0.0.6
179 * @return string Extracted field type.
180 */
181 public static function get_field_type_from_key( $field_key ) {
182
183 if ( false === strpos( $field_key, '-lbl-' ) ) {
184 return '';
185 }
186
187 return trim( explode( '-', $field_key )[1] );
188 }
189
190 /**
191 * Extracts the field label from the dynamic field key ( or field slug ).
192 *
193 * @param string $field_key Dynamic field key.
194 * @since 1.1.1
195 * @return string Extracted field label.
196 */
197 public static function get_field_label_from_key( $field_key ) {
198 if ( false === strpos( $field_key, '-lbl-' ) ) {
199 return '';
200 }
201
202 $label = explode( '-lbl-', $field_key )[1];
203 // Getting the encrypted label. we are removing the block slug here.
204 $label = explode( '-', $label )[0];
205
206 return $label ? html_entity_decode( self::decrypt( $label ) ) : '';
207 }
208
209 /**
210 * Extracts the block ID from the dynamic field key ( or field slug ).
211 *
212 * @param string $field_key Dynamic field key.
213 * @since 1.6.1
214 * @return string Extracted block ID.
215 */
216 public static function get_block_id_from_key( $field_key ) {
217 // Check if the key contains the block ID identifier.
218 if ( strpos( $field_key, 'srfm-' ) === 0 && strpos( $field_key, '-lbl-' ) === false ) {
219 return ''; // Return empty if the key format is invalid.
220 }
221
222 $parts = explode( '-lbl-', $field_key );
223 if ( isset( $parts[0] ) ) {
224 $block_id = explode( '-', $parts[0] );
225 if ( is_array( $block_id ) && ! empty( $block_id ) ) {
226 return end( $block_id );
227 }
228 }
229 return '';
230 }
231
232 /**
233 * Returns the proper sanitize callback functions according to the field type.
234 *
235 * @param string $field_type HTML field type.
236 * @since 0.0.6
237 * @return callable Returns sanitize callbacks according to the provided field type.
238 */
239 public static function get_field_type_sanitize_function( $field_type ) {
240 $callbacks = apply_filters(
241 'srfm_field_type_sanitize_functions',
242 [
243 'url' => 'esc_url_raw',
244 'input' => 'sanitize_text_field',
245 'number' => [ self::class, 'sanitize_number' ],
246 'email' => 'sanitize_email',
247 'textarea' => [ self::class, 'sanitize_textarea' ],
248 ]
249 );
250
251 return $callbacks[ $field_type ] ?? 'sanitize_text_field';
252 }
253
254 /**
255 * Sanitizes a numeric value.
256 *
257 * This function checks if the input value is numeric. If it is numeric, it sanitizes
258 * the value to ensure it's a float or integer, allowing for fractions and thousand separators.
259 * If the value is not numeric, it sanitizes it as a text field.
260 *
261 * @param mixed $value The value to be sanitized.
262 * @since 0.0.6
263 * @return int|float|string The sanitized value.
264 */
265 public static function sanitize_number( $value ) {
266 if ( ! is_numeric( $value ) ) {
267 // phpcs:ignore /** @phpstan-ignore-next-line */
268 return sanitize_text_field( $value ); // If it is not numeric, then let user get some sanitized data to view.
269 }
270
271 // phpcs:ignore /** @phpstan-ignore-next-line */
272 return sanitize_text_field( filter_var( $value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND ) );
273 }
274
275 /**
276 * Sanitize a CSS value to prevent injection.
277 *
278 * Strips characters that can break out of a CSS property value context
279 * and removes dangerous CSS functions while preserving safe ones
280 * (rgb, hsl, linear-gradient, etc.).
281 *
282 * @param mixed $value Raw CSS value.
283 * @return string Sanitized CSS value.
284 * @since 2.7.0
285 */
286 public static function sanitize_css_value( $value ) {
287 $value = self::get_string_value( $value );
288 // Strip characters that can break out of a CSS property value context.
289 $value = preg_replace( '/[{}<>;\\\\"\'`]/', '', $value ) ?? '';
290 // Remove dangerous CSS functions (url, expression, import, etc.) while preserving safe ones (rgb, hsl, linear-gradient, etc.).
291 return preg_replace( '/\b(url|expression|import|javascript)\s*\(/i', '(', $value ) ?? '';
292 }
293
294 /**
295 * This function sanitizes the submitted form data according to the field type.
296 *
297 * @param array<mixed> $form_data $form_data User submitted form data.
298 * @since 0.0.6
299 * @return array<mixed> $result Sanitized form data.
300 */
301 public static function sanitize_by_field_type( $form_data ) {
302 $result = [];
303
304 if ( empty( $form_data ) || ! is_array( $form_data ) ) {
305 return $result;
306 }
307
308 foreach ( $form_data as $field_key => &$value ) {
309 $field_type = self::get_field_type_from_key( $field_key );
310 $sanitize_function = self::get_field_type_sanitize_function( $field_type );
311 $sanitized_data = is_array( $value ) ? self::sanitize_by_field_type( $value ) : call_user_func( $sanitize_function, $value );
312
313 $result[ $field_key ] = $sanitized_data;
314 }
315
316 return $result;
317 }
318
319 /**
320 * This function performs array_map for multi dimensional array
321 *
322 * @param string $function function name to be applied on each element on array.
323 * @param array<mixed> $data_array array on which function needs to be performed.
324 * @return array<mixed>
325 * @since 0.0.1
326 */
327 public static function sanitize_recursively( $function, $data_array ) {
328 $response = [];
329 if ( is_array( $data_array ) ) {
330 if ( ! is_callable( $function ) ) {
331 return $data_array;
332 }
333 foreach ( $data_array as $key => $data ) {
334 $val = is_array( $data ) ? self::sanitize_recursively( $function, $data ) : $function( $data );
335 $response[ $key ] = $val;
336 }
337 }
338
339 return $response;
340 }
341
342 /**
343 * Generates common markup liked label, etc
344 *
345 * @param int|string $form_id form id.
346 * @param string $type Type of form markup.
347 * @param string $label Label for the form markup.
348 * @param string $slug Slug for the form markup.
349 * @param string $block_id Block id for the form markup.
350 * @param bool $required If field is required or not.
351 * @param string $help Help for the form markup.
352 * @param string $error_msg Error message for the form markup.
353 * @param bool $is_unique Check if the field is unique.
354 * @param string $duplicate_msg Duplicate message for field.
355 * @param bool $override Override for error markup.
356 * @return string
357 * @since 0.0.1
358 */
359 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 ) {
360 $duplicate_msg = $duplicate_msg ? ' data-unique-msg="' . esc_attr( $duplicate_msg ) . '"' : '';
361
362 $markup = '';
363 $show_labels_as_placeholder = get_post_meta( self::get_integer_value( $form_id ), '_srfm_use_label_as_placeholder', true );
364 $show_labels_as_placeholder = $show_labels_as_placeholder ? self::get_string_value( $show_labels_as_placeholder ) : false;
365
366 $required_sign = apply_filters( 'srfm_value_after_label_placeholder', ' *' );
367
368 if ( ! is_string( $required_sign ) ) {
369 $required_sign = ' *';
370 }
371
372 switch ( $type ) {
373 case 'label':
374 if ( $label ) {
375 ob_start();
376 ?>
377 <label id="srfm-label-<?php echo esc_attr( $block_id ); ?>" for="srfm-<?php echo esc_attr( $slug ); ?>-<?php echo esc_attr( $block_id ); ?>" class="srfm-block-label">
378 <?php echo wp_kses_post( $label ); ?>
379 <?php if ( $required ) { ?>
380 <span class="srfm-required" aria-hidden="true"> *</span>
381 <?php } ?>
382 </label>
383 <?php
384 $markup = ob_get_clean();
385 }
386 break;
387 case 'help':
388 if ( $help ) {
389 ob_start();
390 ?>
391 <div class="srfm-description" id="srfm-description-<?php echo esc_attr( $block_id ); ?>">
392 <?php echo wp_kses_post( $help ); ?>
393 </div>
394 <?php
395 $markup = ob_get_clean();
396 }
397 break;
398 case 'error':
399 if ( $required || $override ) {
400 ob_start();
401 ?>
402 <div class="srfm-error-message" data-srfm-id="srfm-error-<?php echo esc_attr( $block_id ); ?>" data-error-msg="<?php echo esc_attr( $error_msg ); ?>"<?php echo $duplicate_msg; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
403 <?php echo esc_html( $error_msg ); ?>
404 </div>
405 <?php
406 $markup = ob_get_clean();
407 }
408 break;
409 case 'is_unique':
410 if ( $is_unique ) {
411 ob_start();
412 ?>
413 <div class="srfm-error">
414 <?php echo esc_html( $duplicate_msg ); ?>
415 </div>
416 <?php
417 $markup = ob_get_clean();
418 }
419 break;
420 case 'placeholder':
421 $markup = $label && '1' === $show_labels_as_placeholder ? wp_kses_post( $label ) . ( $required ? esc_attr( $required_sign ) : '' ) : '';
422 break;
423 case 'label_text':
424 // This has been added for generating label text for the form markup instead of adding it in the label tag.
425 if ( $label ) {
426 ob_start();
427 ?>
428 <?php echo wp_kses_post( $label ); ?>
429 <?php if ( $required ) { ?>
430 <span class="srfm-required" aria-hidden="true"> *</span>
431 <?php } ?>
432 <?php
433 $markup = ob_get_clean();
434 }
435 break;
436 default:
437 $markup = '';
438 }
439
440 return is_string( $markup ) ? $markup : '';
441 }
442
443 /**
444 * Get an SVG Icon
445 *
446 * @since 0.0.1
447 * @param string $icon the icon name.
448 * @param string $class if the baseline class should be added.
449 * @param string $html Custom attributes inside svg wrapper.
450 * @return string
451 */
452 public static function fetch_svg( $icon = '', $class = '', $html = '' ) {
453 $class = $class ? ' ' . $class : '';
454
455 if ( ! self::$srfm_svgs ) {
456 ob_start();
457
458 include_once SRFM_DIR . 'assets/svg/svgs.json';
459 self::$srfm_svgs = json_decode( self::get_string_value( ob_get_clean() ), true );
460 self::$srfm_svgs = apply_filters( 'srfm_svg_icons', self::$srfm_svgs );
461 }
462
463 ob_start();
464 ?>
465 <span class="srfm-icon<?php echo esc_attr( $class ); ?>" <?php echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
466 <?php echo self::$srfm_svgs[ $icon ] ?? ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
467 </span>
468 <?php
469 $output = ob_get_clean();
470 return is_string( $output ) ? $output : '';
471 }
472
473 /**
474 * Encrypt data using base64.
475 *
476 * @param string $input The input string which needs to be encrypted.
477 * @since 0.0.1
478 * @return string The encrypted string.
479 */
480 public static function encrypt( $input ) {
481 // If the input is empty or not a string, then abandon ship.
482 if ( empty( $input ) || ! is_string( $input ) ) {
483 return '';
484 }
485
486 // Strip HTML tags to prevent them from being included in IDs and field names.
487 $input = wp_strip_all_tags( $input );
488
489 // Encrypt the input and return it.
490 $base_64 = base64_encode( $input ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
491 return rtrim( $base_64, '=' );
492 }
493
494 /**
495 * Decrypt data using base64.
496 *
497 * @param string $input The input string which needs to be decrypted.
498 * @since 0.0.1
499 * @return string The decrypted string.
500 */
501 public static function decrypt( $input ) {
502 // If the input is empty or not a string, then abandon ship.
503 if ( empty( $input ) || ! is_string( $input ) ) {
504 return '';
505 }
506
507 // Decrypt the input and return it.
508 $base_64 = $input . str_repeat( '=', strlen( $input ) % 4 );
509 return base64_decode( $base_64 ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
510 }
511
512 /**
513 * Update an option from the database.
514 *
515 * @param string $key The option key.
516 * @param mixed $value The value to update.
517 * @param bool $network_override Whether to allow the network_override admin setting to be overridden on subsites.
518 * @since 0.0.1
519 * @return bool True if the option was updated, false otherwise.
520 */
521 public static function update_admin_settings_option( $key, $value, $network_override = false ) {
522 // Update the site-wide option if we're in the network admin, and return the updated status.
523 return $network_override && is_multisite() ? update_site_option( $key, $value ) : update_option( $key, $value );
524 }
525
526 /**
527 * Update an option from the database.
528 *
529 * @param int|string $post_id post id / form id.
530 * @param string $key meta key name.
531 * @param bool $single single or multiple.
532 * @param mixed $default default value.
533 *
534 * @since 0.0.1
535 * @return string Meta value.
536 */
537 public static function get_meta_value( $post_id, $key, $single = true, $default = '' ) {
538 $srfm_live_mode_data = self::get_instant_form_live_data();
539
540 if ( isset( $srfm_live_mode_data[ $key ] ) ) {
541 // Give priority to live mode data if we have one set from the Instant Form.
542 return self::get_string_value( $srfm_live_mode_data[ $key ] );
543 }
544
545 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 );
546 }
547
548 /**
549 * Wrapper for the WordPress's get_post_meta function with the support for default values.
550 *
551 * @param int|string $post_id Post ID.
552 * @param string $key The meta key to retrieve.
553 * @param mixed $default Default value.
554 * @param bool $single Optional. Whether to return a single value.
555 * @since 0.0.8
556 * @return mixed Meta value.
557 */
558 public static function get_post_meta( $post_id, $key, $default = null, $single = true ) {
559 $meta_value = get_post_meta( self::get_integer_value( $post_id ), $key, $single );
560 return $meta_value ? $meta_value : $default;
561 }
562
563 /**
564 * Returns query params data for instant form live preview.
565 *
566 * @since 0.0.8
567 * @return array<mixed> Live preview data.
568 */
569 public static function get_instant_form_live_data() {
570 $srfm_live_mode_data = isset( $_GET['live_mode'] ) && self::current_user_can() ? self::sanitize_recursively( 'sanitize_text_field', wp_unslash( $_GET ) ) : []; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification is not needed here.
571
572 return $srfm_live_mode_data ? array_map(
573 // Normalize falsy values.
574 static function( $live_data ) {
575 return 'false' === $live_data ? false : $live_data;
576 },
577 $srfm_live_mode_data
578 ) : [];
579 }
580
581 /**
582 * Default dynamic block value.
583 *
584 * @since 0.0.1
585 * @return array<string> Meta value.
586 */
587 public static function default_dynamic_block_option() {
588
589 $common_err_msg = self::get_common_err_msg();
590
591 $default_values = [
592 'srfm_url_block_required_text' => $common_err_msg['required'],
593 'srfm_input_block_required_text' => $common_err_msg['required'],
594 'srfm_input_block_unique_text' => $common_err_msg['unique'],
595 'srfm_address_block_required_text' => $common_err_msg['required'],
596 'srfm_phone_block_required_text' => $common_err_msg['required'],
597 'srfm_phone_block_unique_text' => $common_err_msg['unique'],
598 'srfm_number_block_required_text' => $common_err_msg['required'],
599 'srfm_textarea_block_required_text' => $common_err_msg['required'],
600 'srfm_multi_choice_block_required_text' => $common_err_msg['required'],
601 'srfm_checkbox_block_required_text' => $common_err_msg['required'],
602 'srfm_gdpr_block_required_text' => $common_err_msg['required'],
603 'srfm_email_block_required_text' => $common_err_msg['required'],
604 'srfm_email_block_unique_text' => $common_err_msg['unique'],
605 'srfm_dropdown_block_required_text' => $common_err_msg['required'],
606 'srfm_rating_block_required_text' => $common_err_msg['required'],
607 ];
608
609 $default_values = array_merge( $default_values, Translatable::dynamic_validation_messages() );
610
611 return apply_filters( 'srfm_default_dynamic_block_option', $default_values, $common_err_msg );
612 }
613
614 /**
615 * Get default dynamic block value.
616 *
617 * @param string $key meta key name.
618 * @since 0.0.1
619 * @return string Meta value.
620 */
621 public static function get_default_dynamic_block_option( $key ) {
622 $default_dynamic_values = self::default_dynamic_block_option();
623 $option = get_option( 'srfm_default_dynamic_block_option', $default_dynamic_values );
624
625 if ( is_array( $option ) && array_key_exists( $key, $option ) ) {
626 return $option[ $key ];
627 }
628 return '';
629 }
630
631 /**
632 * Checks whether a given request has appropriate permissions.
633 *
634 * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
635 * @since 0.0.1
636 */
637 public static function get_items_permissions_check() {
638 if ( self::current_user_can() ) {
639 return true;
640 }
641
642 return new WP_Error(
643 'rest_cannot_view',
644 __( 'Sorry, you are not allowed to perform this action.', 'sureforms' ),
645 [ 'status' => \rest_authorization_required_code() ]
646 );
647 }
648
649 /**
650 * Check if the current user has a given capability.
651 *
652 * @param string $capability The capability to check.
653 * @param array<mixed> $args Optional. Additional arguments to pass to the capability check.
654 *
655 * @since 0.0.3
656 * @return bool Whether the current user has the given capability or role.
657 */
658 public static function current_user_can( $capability = '', $args = [] ) {
659 if ( ! function_exists( 'current_user_can' ) ) {
660 return false;
661 }
662
663 if ( ! is_string( $capability ) || empty( $capability ) ) {
664 $capability = 'manage_options';
665 }
666
667 return ! empty( $args ) && is_array( $args ) && count( $args ) > 0
668 ? current_user_can( $capability, ...$args )
669 : current_user_can( $capability );
670 }
671
672 /**
673 * Get all the entries for the given form ids. The entries are older than the given days_old.
674 *
675 * @param int $days_old The number of days old the entries should be.
676 * @param array<int> $sf_form_ids The form ids for which the entries need to be fetched.
677 * @since 0.0.2
678 * @return array<mixed> the entries matching the criteria.
679 */
680 public static function get_entries_from_form_ids( $days_old = 0, $sf_form_ids = [] ) {
681
682 $entries = [];
683 $days_old_date = ( new \DateTime() )->modify( "-{$days_old} days" )->format( 'Y-m-d H:i:s' );
684
685 foreach ( $sf_form_ids as $form_id ) {
686 // args according to the get_all() function in the Entries class.
687 $args = [
688 'where' => [
689 [
690 [
691 'key' => 'form_id',
692 'value' => $form_id,
693 'compare' => '=',
694 ],
695 [
696 'key' => 'created_at',
697 'value' => $days_old_date,
698 'compare' => '<=',
699 ],
700 ],
701 ],
702 ];
703
704 // store all the entries in a single array.
705 $entries = array_merge( $entries, Entries::get_all( $args, false ) );
706 }
707 return $entries;
708 }
709
710 /**
711 * Decode block attributes.
712 * The function reverses the effect of serialize_block_attributes()
713 *
714 * @link https://developer.wordpress.org/reference/functions/serialize_block_attributes/
715 * @param string $encoded_data the encoded block attribute.
716 * @since 0.0.2
717 * @return string decoded block attribute
718 */
719 public static function decode_block_attribute( $encoded_data = '' ) {
720 $decoded_data = preg_replace( '/\\\\u002d\\\\u002d/', '--', self::get_string_value( $encoded_data ) );
721 $decoded_data = preg_replace( '/\\\\u003c/', '<', self::get_string_value( $decoded_data ) );
722 $decoded_data = preg_replace( '/\\\\u003e/', '>', self::get_string_value( $decoded_data ) );
723 $decoded_data = preg_replace( '/\\\\u0026/', '&', self::get_string_value( $decoded_data ) );
724 $decoded_data = preg_replace( '/\\\\\\\\"/', '"', self::get_string_value( $decoded_data ) );
725 return self::get_string_value( $decoded_data );
726 }
727
728 /**
729 * Map slugs to submission data.
730 *
731 * @param array<mixed> $submission_data submission_data.
732 * @since 0.0.3
733 * @return array<mixed>
734 */
735 public static function map_slug_to_submission_data( $submission_data = [] ) {
736 $mapped_data = [];
737 foreach ( $submission_data as $key => $value ) {
738 if ( false === strpos( $key, '-lbl-' ) ) {
739 continue;
740 }
741 $label = explode( '-lbl-', $key )[1];
742 $slug = implode( '-', array_slice( explode( '-', $label ), 1 ) );
743
744 /**
745 * Filters whether a field should be skipped when mapping slugs to submission data.
746 *
747 * This filter allows plugins or custom code to determine if a field should be excluded
748 * from the mapped submission data array (such as for internal fields or extraneous meta).
749 *
750 * @since 2.0.0
751 *
752 * @param bool $skip_this_field Whether to skip this field from processing. Default false.
753 * @param array $args {
754 * Arguments used for this field.
755 *
756 * @type string $key The original key of the field in the submission data array.
757 * @type string $slug The mapped slug parsed from the field key.
758 * @type mixed $value The value assigned to this field.
759 * }
760 */
761 $skip_this_field = apply_filters(
762 'srfm_map_slug_to_submission_data_should_skip',
763 false,
764 [
765 'key' => $key,
766 'slug' => $slug,
767 'value' => $value,
768 ]
769 );
770
771 if ( $skip_this_field ) {
772 continue;
773 }
774
775 // Check if value is array to handle external package field functionality.
776 // like repeater fields that need special processing.
777 if ( is_array( $value ) && ! empty( $value ) ) {
778 // Apply filter to allow external packages to process array values.
779 // Returns processed data with 'is_processed' flag if successfully handled.
780 $filtered_submission_data = apply_filters(
781 'srfm_map_slug_to_submission_data_array',
782 [
783 'value' => $value,
784 'key' => $key,
785 'slug' => $slug,
786 ]
787 );
788 if ( isset( $filtered_submission_data['is_processed'] ) && true === $filtered_submission_data['is_processed'] ) {
789 $mapped_data[ $slug ] = $filtered_submission_data['value'];
790 continue;
791 }
792 }
793
794 // If the value is an array (e.g. multi-upload field), decode each URL value.
795 if ( is_array( $value ) ) {
796 $mapped_data[ $slug ] = array_map(
797 static function ( $val ) {
798 return is_string( $val ) ? rawurldecode( $val ) : $val;
799 },
800 $value
801 );
802 continue;
803 }
804
805 $mapped_data[ $slug ] = is_string( $value ) ? html_entity_decode( esc_attr( $value ) ) : $value;
806 }
807 return $mapped_data;
808 }
809
810 /**
811 * Get forms options. Shows all the available forms in the dropdown.
812 *
813 * @since 0.0.5
814 * @param string $key Determines the type of data to return.
815 * @return array<mixed>
816 */
817 public static function get_sureforms( $key = '' ) {
818 $forms = get_posts(
819 apply_filters(
820 'srfm_get_sureforms_query_args',
821 [
822 'post_type' => SRFM_FORMS_POST_TYPE,
823 'posts_per_page' => -1,
824 'post_status' => 'publish',
825 ]
826 )
827 );
828
829 $options = [];
830
831 foreach ( $forms as $form ) {
832 if ( $form instanceof WP_Post ) {
833 if ( 'all' === $key ) {
834 $options[ $form->ID ] = $form;
835 } elseif ( ! empty( $key ) && is_string( $key ) && isset( $form->$key ) ) {
836 $options[ $form->ID ] = $form->$key;
837 } else {
838 $options[ $form->ID ] = $form->post_title;
839 }
840 }
841 }
842
843 return $options;
844 }
845
846 /**
847 * Get all the forms.
848 *
849 * @since 0.0.5
850 * @return array<mixed>
851 */
852 public static function get_sureforms_title_with_ids() {
853 $form_options = self::get_sureforms();
854
855 foreach ( $form_options as $key => $value ) {
856 $form_options[ $key ] = $value . ' #' . $key;
857 }
858
859 return $form_options;
860 }
861
862 /**
863 * Get the CSS variables based on different field spacing sizes.
864 *
865 * @param string|null $field_spacing The field spacing size or boolean false to return complete sizes array.
866 *
867 * @since 0.0.7
868 * @return array<string|mixed>
869 */
870 public static function get_css_vars( $field_spacing = null ) {
871 /**
872 * $sizes - Field Spacing Sizes Variables.
873 * The array contains the CSS variables for different field spacing sizes.
874 * Each key corresponds to the field spacing size, and the value is an array of CSS variables.
875 *
876 * For future variables depending on the field spacing size, add the variable to the array respectively.
877 */
878 $sizes = apply_filters(
879 'srfm_css_vars_sizes',
880 [
881 'small' => [
882 '--srfm-row-gap-between-blocks' => '16px',
883 // Address block gap and spacing variables.
884 '--srfm-address-label-font-size' => '14px',
885 '--srfm-address-label-line-height' => '20px',
886 '--srfm-address-description-font-size' => '12px',
887 '--srfm-address-description-line-height' => '16px',
888 '--srfm-col-gap-between-fields' => '12px',
889 '--srfm-row-gap-between-fields' => '12px',
890 '--srfm-gap-below-address-label' => '12px',
891 // Dropdown Variables.
892 '--srfm-dropdown-font-size' => '14px',
893 '--srfm-dropdown-gap-between-input-menu' => '4px',
894 '--srfm-dropdown-badge-padding' => '2px 6px',
895 '--srfm-dropdown-multiselect-font-size' => '12px',
896 '--srfm-dropdown-multiselect-line-height' => '16px',
897 '--srfm-dropdown-padding-right' => '12px',
898 // initial padding and from 20px - 12px for dropdown arrow width and 8px for gap before dropdown arrow.
899 '--srfm-dropdown-padding-right-icon' => 'calc( var( --srfm-dropdown-padding-right ) + 20px )',
900 '--srfm-dropdown-multiselect-padding' => '8px var( --srfm-dropdown-padding-right-icon ) 8px 8px',
901 // Input Field Variables.
902 '--srfm-input-height' => '40px',
903 '--srfm-input-field-padding' => '10px 12px',
904 '--srfm-input-field-font-size' => '14px',
905 '--srfm-input-field-line-height' => '20px',
906 '--srfm-input-field-margin-top' => '4px',
907 '--srfm-input-field-margin-bottom' => '4px',
908 // Checkbox and GDPR Variables.
909 '--srfm-checkbox-label-font-size' => '14px',
910 '--srfm-checkbox-label-line-height' => '20px',
911 '--srfm-checkbox-description-font-size' => '12px',
912 '--srfm-checkbox-description-line-height' => '16px',
913 '--srfm-check-ctn-width' => '16px',
914 '--srfm-check-ctn-height' => '16px',
915 '--srfm-check-svg-size' => '10px',
916 '--srfm-checkbox-margin-top-frontend' => '2px',
917 '--srfm-checkbox-margin-top-editor' => '3px',
918 '--srfm-check-gap' => '8px',
919 '--srfm-checkbox-description-margin-left' => '24px',
920 // Phone Number field variables.
921 '--srfm-flag-section-padding' => '10px 0 10px 12px',
922 '--srfm-gap-between-icon-text' => '8px',
923 // Label Variables.
924 '--srfm-label-font-size' => '14px',
925 '--srfm-label-line-height' => '20px',
926 // Description Variables.
927 '--srfm-description-font-size' => '12px',
928 '--srfm-description-line-height' => '16px',
929 // Button Variables.
930 '--srfm-btn-padding' => '8px 14px',
931 '--srfm-btn-font-size' => '14px',
932 '--srfm-btn-line-height' => '20px',
933 // Multi Choice Variables.
934 '--srfm-multi-choice-horizontal-padding' => '16px',
935 '--srfm-multi-choice-vertical-padding' => '16px',
936 '--srfm-multi-choice-internal-option-gap' => '8px',
937 '--srfm-multi-choice-vertical-svg-size' => '32px',
938 '--srfm-multi-choice-horizontal-image-size' => '20px',
939 '--srfm-multi-choice-vertical-image-size' => '100px',
940 '--srfm-multi-choice-outer-padding' => '0',
941 ],
942 'medium' => [
943 '--srfm-row-gap-between-blocks' => '18px',
944 // Address block gap and spacing variables.
945 '--srfm-address-label-font-size' => '16px',
946 '--srfm-address-label-line-height' => '24px',
947 '--srfm-address-description-font-size' => '14px',
948 '--srfm-address-description-line-height' => '20px',
949 '--srfm-col-gap-between-fields' => '16px',
950 '--srfm-row-gap-between-fields' => '16px',
951 '--srfm-gap-below-address-label' => '14px',
952 // Input Field Variables.
953 '--srfm-input-height' => '44px',
954 '--srfm-input-field-font-size' => '16px',
955 '--srfm-input-field-line-height' => '24px',
956 '--srfm-input-field-margin-top' => '6px',
957 '--srfm-input-field-margin-bottom' => '6px',
958 // Checkbox and GDPR Variables.
959 '--srfm-checkbox-label-font-size' => '16px',
960 '--srfm-checkbox-label-line-height' => '24px',
961 '--srfm-checkbox-description-font-size' => '14px',
962 '--srfm-checkbox-description-line-height' => '20px',
963 '--srfm-checkbox-margin-top-frontend' => '4px',
964 '--srfm-checkbox-margin-top-editor' => '6px',
965 '--srfm-checkbox-description-margin-left' => '24px',
966 // Label Variables.
967 '--srfm-label-font-size' => '16px',
968 '--srfm-label-line-height' => '24px',
969 // Description Variables.
970 '--srfm-description-font-size' => '14px',
971 '--srfm-description-line-height' => '20px',
972 // Button Variables.
973 '--srfm-btn-padding' => '10px 14px',
974 '--srfm-btn-font-size' => '16px',
975 '--srfm-btn-line-height' => '24px',
976 // Multi Choice Variables.
977 '--srfm-multi-choice-horizontal-padding' => '20px',
978 '--srfm-multi-choice-vertical-padding' => '20px',
979 '--srfm-multi-choice-vertical-svg-size' => '40px',
980 '--srfm-multi-choice-horizontal-image-size' => '24px',
981 '--srfm-multi-choice-vertical-image-size' => '120px',
982 '--srfm-multi-choice-outer-padding' => '2px',
983 ],
984 'large' => [
985 '--srfm-row-gap-between-blocks' => '20px',
986 // Address Block Gap and Spacing Variables.
987 '--srfm-address-label-font-size' => '18px',
988 '--srfm-address-label-line-height' => '28px',
989 '--srfm-address-description-font-size' => '16px',
990 '--srfm-address-description-line-height' => '24px',
991 '--srfm-col-gap-between-fields' => '16px',
992 '--srfm-row-gap-between-fields' => '20px',
993 '--srfm-gap-below-address-label' => '16px',
994 // Dropdown Variables.
995 '--srfm-dropdown-font-size' => '16px',
996 '--srfm-dropdown-gap-between-input-menu' => '6px',
997 '--srfm-dropdown-badge-padding' => '6px 6px',
998 '--srfm-dropdown-multiselect-font-size' => '14px',
999 '--srfm-dropdown-multiselect-line-height' => '20px',
1000 '--srfm-dropdown-padding-right' => '14px',
1001 // Input Field Variables.
1002 '--srfm-input-height' => '48px',
1003 '--srfm-input-field-padding' => '10px 14px',
1004 '--srfm-input-field-font-size' => '18px',
1005 '--srfm-input-field-line-height' => '28px',
1006 '--srfm-input-field-margin-top' => '8px',
1007 '--srfm-input-field-margin-bottom' => '8px',
1008 // Checkbox and GDPR Variables.
1009 '--srfm-checkbox-label-font-size' => '18px',
1010 '--srfm-checkbox-label-line-height' => '28px',
1011 '--srfm-checkbox-description-font-size' => '16px',
1012 '--srfm-checkbox-description-line-height' => '24px',
1013 '--srfm-check-ctn-width' => '20px',
1014 '--srfm-check-ctn-height' => '20px',
1015 '--srfm-check-svg-size' => '14px',
1016 '--srfm-check-gap' => '10px',
1017 '--srfm-checkbox-margin-top-frontend' => '4px',
1018 '--srfm-checkbox-margin-top-editor' => '5px',
1019 '--srfm-checkbox-description-margin-left' => '30px',
1020 // Label Variables.
1021 '--srfm-label-font-size' => '18px',
1022 '--srfm-label-line-height' => '28px',
1023 // Description Variables.
1024 '--srfm-description-font-size' => '16px',
1025 '--srfm-description-line-height' => '24px',
1026 // Button Variables.
1027 '--srfm-btn-padding' => '10px 14px',
1028 '--srfm-btn-font-size' => '18px',
1029 '--srfm-btn-line-height' => '28px',
1030 // Multi Choice Variables.
1031 '--srfm-multi-choice-horizontal-padding' => '24px',
1032 '--srfm-multi-choice-vertical-padding' => '24px',
1033 '--srfm-multi-choice-internal-option-gap' => '12px',
1034 '--srfm-multi-choice-vertical-svg-size' => '48px',
1035 '--srfm-multi-choice-horizontal-image-size' => '28px',
1036 '--srfm-multi-choice-vertical-image-size' => '140px',
1037 '--srfm-multi-choice-outer-padding' => '4px',
1038 ],
1039 ]
1040 );
1041 // Return complete sizes array if field_spacing is false. Required in case of JS for Editor changes.
1042 if ( ! $field_spacing ) {
1043 return $sizes;
1044 }
1045
1046 $selected_size = $sizes['small'];
1047 if ( 'small' !== $field_spacing && isset( $sizes[ $field_spacing ] ) ) {
1048 $selected_size = array_merge( $selected_size, $sizes[ $field_spacing ] );
1049 }
1050
1051 return $selected_size;
1052 }
1053
1054 /**
1055 * Array of SureForms blocks which get have user input.
1056 *
1057 * @since 0.0.10
1058 * @return array<string>
1059 */
1060 public static function get_sureforms_blocks() {
1061 return apply_filters(
1062 'srfm_blocks',
1063 [
1064 'srfm/input',
1065 'srfm/email',
1066 'srfm/textarea',
1067 'srfm/number',
1068 'srfm/checkbox',
1069 'srfm/gdpr',
1070 'srfm/phone',
1071 'srfm/address',
1072 'srfm/dropdown',
1073 'srfm/multi-choice',
1074 'srfm/radio',
1075 'srfm/submit',
1076 'srfm/url',
1077 'srfm/payment',
1078 ]
1079 );
1080 }
1081
1082 /**
1083 * Render a site key missing error message.
1084 *
1085 * @param string $provider_name Name of the captcha provider (e.g., HCaptcha, Google reCAPTCHA, Turnstile).
1086 * @since 1.7.0
1087 * @since 1.7.1 moved to inc/helper.php from inc/generate-form-markup.php
1088 * @return void
1089 */
1090 public static function render_missing_sitekey_error( $provider_name ) {
1091 $icon = self::fetch_svg( 'info_circle', '', 'aria-hidden="true"' );
1092 ?>
1093 <p id="sitekey-error" class="srfm-common-error-message srfm-error-message">
1094 <?php echo wp_kses( $icon, self::$allowed_tags_svg ); ?>
1095 <span class="srfm-error-content">
1096 <?php
1097 echo esc_html(
1098 sprintf(
1099 /* translators: %s: Provider name like HCaptcha, Google reCAPTCHA, Turnstile */
1100 __( '%s sitekey is missing. Please contact your site administrator.', 'sureforms' ),
1101 $provider_name
1102 )
1103 );
1104 ?>
1105 </span>
1106 </p>
1107 <?php
1108 }
1109
1110 /**
1111 * Parse and sanitize an email list string which may contain:
1112 *
1113 * @param string $input email addresses.
1114 * @since 1.13.2
1115 * @return string Sanitized email header string.
1116 */
1117 public static function sanitize_email_header( $input ) {
1118 if ( empty( $input ) ) {
1119 return '';
1120 }
1121
1122 $parts = explode( ',', $input );
1123 $output = [];
1124
1125 foreach ( $parts as $part ) {
1126 $part = trim( $part );
1127
1128 // Match "Name <email>".
1129 if ( preg_match( '/^(.*)<(.+)>$/', $part, $matches ) ) {
1130 $name = trim( $matches[1], "\" \t\n\r\0\x0B" ); // trim quotes.
1131 $email = sanitize_email( trim( $matches[2] ) );
1132
1133 if ( is_email( $email ) ) {
1134 $safe_name = sanitize_text_field( $name );
1135 $output[] = $safe_name . ' <' . $email . '>';
1136 }
1137 } else {
1138 // Plain email case.
1139 $email = sanitize_email( $part );
1140 if ( is_email( $email ) ) {
1141 $output[] = $email;
1142 }
1143 }
1144 }
1145
1146 return ! empty( $output ) ? implode( ', ', $output ) : '';
1147 }
1148
1149 /**
1150 * Process blocks and inner blocks.
1151 *
1152 * @param array<mixed> $blocks The block data.
1153 * @param array<string> $slugs The array of existing slugs.
1154 * @param bool $updated The array of existing slugs.
1155 * @param string $prefix The array of existing slugs.
1156 * @param bool $skip_checking_existing_slug Skips the checking of existing slug if passed true. More information documented inside this function.
1157 * @since 0.0.10
1158 * @return array
1159 */
1160 public static function process_blocks( $blocks, &$slugs, &$updated, $prefix = '', $skip_checking_existing_slug = false ) {
1161
1162 if ( ! is_array( $blocks ) ) {
1163 return [ $blocks, $slugs, $updated ];
1164 }
1165
1166 foreach ( $blocks as $index => $block ) {
1167
1168 if ( ! is_array( $block ) ) {
1169 continue;
1170 }
1171 // Checking only for SureForms blocks which can have user input.
1172 if ( empty( $block['blockName'] ) || ! in_array( $block['blockName'], self::get_sureforms_blocks(), true ) ) {
1173 continue;
1174 }
1175
1176 /**
1177 * Lets continue if slug already exists.
1178 * This will ensure that we don't update already existing slugs.
1179 */
1180 if ( isset( $block['attrs'] ) && ! empty( $block['attrs']['slug'] ) && ! in_array( $block['attrs']['slug'], $slugs, true ) ) {
1181
1182 // Made it associative array, so that we can directly check it using block_id rather than mapping or using "in_array" for the checks.
1183 $slugs[ $block['attrs']['block_id'] ] = self::get_string_value( $block['attrs']['slug'] );
1184
1185 if ( is_array( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) ) {
1186 [ $blocks[ $index ]['innerBlocks'], $slugs, $updated ] = self::process_blocks( $block['innerBlocks'], $slugs, $updated, '' );
1187 }
1188 continue;
1189 }
1190
1191 if ( $skip_checking_existing_slug && empty( $block['innerBlocks'] ) && isset( $slugs[ $block['attrs']['block_id'] ] ) ) {
1192 /**
1193 * Skip re-processing of the already process or existing slugs if above parameter "$skip_checking_existing_slug" is passed as true.
1194 * This is helpful in the scenarios where we need to compare and verify between already saved blocks and new unsaved blocks parsed
1195 * from the contents.
1196 *
1197 * However, it is also necessary to make sure if that current block is not a parent / wrapper block
1198 * by checking "$block['innerBlocks']" empty.
1199 *
1200 * And finally, checking if the block-id "$block['attrs']['block_id']" is already set in the list of "$slugs",
1201 * making sure that we are only processing the new blocks.
1202 */
1203 continue;
1204 }
1205
1206 if ( is_array( $blocks[ $index ]['attrs'] ) ) {
1207
1208 $blocks[ $index ]['attrs']['slug'] = self::generate_unique_block_slug( $block, $slugs, $prefix );
1209 $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.
1210 $updated = true;
1211 if ( is_array( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) ) {
1212
1213 [ $blocks[ $index ]['innerBlocks'], $slugs, $updated ] = self::process_blocks( $block['innerBlocks'], $slugs, $updated, $blocks[ $index ]['attrs']['slug'] );
1214
1215 }
1216 }
1217 }
1218 return [ $blocks, $slugs, $updated ];
1219 }
1220
1221 /**
1222 * Generates slug based on the provided block and existing slugs.
1223 *
1224 * @param array<mixed> $block The block data.
1225 * @param array<string> $slugs The array of existing slugs.
1226 * @param string $prefix The array of existing slugs.
1227 * @since 0.0.10
1228 * @return string The generated unique block slug.
1229 */
1230 public static function generate_unique_block_slug( $block, $slugs, $prefix ) {
1231 $slug = is_string( $block['blockName'] ) ? $block['blockName'] : '';
1232
1233 if ( ! empty( $block['attrs']['label'] ) && is_string( $block['attrs']['label'] ) ) {
1234 $slug = sanitize_title( $block['attrs']['label'] );
1235 }
1236
1237 if ( ! empty( $prefix ) ) {
1238 $slug = $prefix . '-' . $slug;
1239 }
1240
1241 return self::generate_slug( $slug, $slugs );
1242 }
1243
1244 /**
1245 * This function ensures that the slug is unique.
1246 * If the slug is already taken, it appends a number to the slug to make it unique.
1247 *
1248 * @param string $slug test to be converted to slug.
1249 * @param array<string> $slugs An array of existing slugs.
1250 * @since 0.0.10
1251 * @return string The unique slug.
1252 */
1253 public static function generate_slug( $slug, $slugs ) {
1254 $slug = sanitize_title( $slug );
1255
1256 if ( ! in_array( $slug, $slugs, true ) ) {
1257 return $slug;
1258 }
1259
1260 $index = 1;
1261
1262 while ( in_array( $slug . '-' . $index, $slugs, true ) ) {
1263 $index++;
1264 }
1265
1266 return $slug . '-' . $index;
1267 }
1268
1269 /**
1270 * Encode data to JSON. This function will encode the data with JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE.
1271 *
1272 * @since 0.0.11
1273 * @param array<mixed> $data The data to encode.
1274 * @return string|false The JSON representation of the value on success or false on failure.
1275 */
1276 public static function encode_json( $data ) {
1277 return wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
1278 }
1279
1280 /**
1281 * Returns true if SureTriggers plugin is ready for the custom app.
1282 *
1283 * @since 1.0.3
1284 * @return bool Returns true if SureTriggers plugin is ready for the custom app.
1285 */
1286 public static function is_suretriggers_ready() {
1287 if ( ! defined( 'SURE_TRIGGERS_FILE' ) ) {
1288 // Probably plugin is de-activated or not installed at all.
1289 return false;
1290 }
1291
1292 $suretriggers_data = get_option( 'suretrigger_options', [] );
1293 if ( ! is_array( $suretriggers_data ) || empty( $suretriggers_data['secret_key'] ) || ! is_string( $suretriggers_data['secret_key'] ) ) {
1294 // SureTriggers is not authenticated yet.
1295 return false;
1296 }
1297
1298 return true;
1299 }
1300
1301 /**
1302 * Registers script translations for a specific handle.
1303 *
1304 * This function sets the script translations for a given script handle, allowing
1305 * localization of JavaScript strings using the specified text domain and path.
1306 *
1307 * @param string $handle The script handle to apply translations to.
1308 * @param string $domain Optional. The text domain for translations. Default is 'sureforms'.
1309 * @param string $path Optional. The path to the translation files. Default is the 'languages' folder in the SureForms directory.
1310 *
1311 * @since 1.0.5
1312 * @return void
1313 */
1314 public static function register_script_translations( $handle, $domain = 'sureforms', $path = SRFM_DIR . 'languages' ) {
1315 wp_set_script_translations( $handle, $domain, $path );
1316 }
1317
1318 /**
1319 * Validates whether the specified conditions or a single key-value pair exist in the request context.
1320 *
1321 * - If `$conditions` is provided as an array, it will validate all key-value pairs in `$conditions`
1322 * against the `$_REQUEST` superglobal.
1323 * - If `$conditions` is empty, it validates a single key-value pair from `$key` and `$value`.
1324 *
1325 * @param string $value The expected value to match in the request if `$conditions` is not used.
1326 * @param string $key The key to check for in the request if `$conditions` is not used.
1327 * @param array<string, string> $conditions An optional associative array of key-value pairs to validate.
1328 * @since 1.1.1
1329 * @return bool Returns true if all conditions are met or the single key-value pair is valid, otherwise false.
1330 */
1331 public static function validate_request_context( $value, $key = 'post_type', $conditions = [] ) {
1332 // If conditions are provided, validate all key-value pairs in the conditions array.
1333 if ( ! empty( $conditions ) ) {
1334 foreach ( $conditions as $condition_key => $condition_value ) {
1335 if ( ! isset( $_REQUEST[ $condition_key ] ) || $_REQUEST[ $condition_key ] !== $condition_value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a controlled comparison of request values.
1336 // Return false if any condition is not satisfied.
1337 return false;
1338 }
1339 }
1340 // Return true if all conditions are satisfied.
1341 return true;
1342 }
1343
1344 // Validate $value and $key when no conditions are provided.
1345 if ( empty( $key ) || empty( $value ) ) {
1346 return false;
1347 }
1348
1349 // Validate a single key-value pair when no conditions are provided.
1350 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.
1351 }
1352
1353 /**
1354 * Retrieve the list of excluded fields for form data processing.
1355 *
1356 * This method returns an array of field keys that should be excluded when
1357 * processing form data.
1358 *
1359 * @since 1.1.1
1360 * @return array<string> Returns the string array of excluded fields.
1361 */
1362 public static function get_excluded_fields() {
1363 $excluded_fields = [ 'srfm-honeypot-field', 'g-recaptcha-response', 'srfm-sender-email-field', 'form-id' ];
1364
1365 return apply_filters( 'srfm_excluded_fields', $excluded_fields );
1366 }
1367
1368 /**
1369 * Check whether the current page is a SureForms admin page.
1370 *
1371 * @since 1.2.2
1372 * @return bool Returns true if the current page is a SureForms admin page, otherwise false.
1373 */
1374 public static function is_sureforms_admin_page() {
1375 $current_screen = get_current_screen();
1376 $is_screen_sureforms_menu = self::validate_request_context( 'sureforms_menu', 'page' );
1377 $is_screen_add_new_form = self::validate_request_context( 'add-new-form', 'page' );
1378 $is_screen_sureforms_form_settings = self::validate_request_context( 'sureforms_form_settings', 'page' );
1379 $is_screen_sureforms_entries = self::validate_request_context( SRFM_ENTRIES, 'page' );
1380 $is_post_type_sureforms_form = $current_screen && SRFM_FORMS_POST_TYPE === $current_screen->post_type;
1381
1382 return $is_screen_sureforms_menu || $is_screen_add_new_form || $is_screen_sureforms_form_settings || $is_screen_sureforms_entries || $is_post_type_sureforms_form;
1383 }
1384
1385 /**
1386 * Filters and concatenates valid class names from an array.
1387 *
1388 * @param array<string> $class_names The array containing potential class names.
1389 * @since 1.4.0
1390 * @return string The concatenated string of valid class names separated by spaces.
1391 */
1392 public static function join_strings( $class_names ) {
1393 // Filter the array to include only valid class names.
1394 $valid_class_names = array_filter(
1395 $class_names,
1396 static function ( $value ) {
1397 return is_string( $value ) && '' !== $value && false !== $value;
1398 }
1399 );
1400
1401 // Concatenate the valid class names with spaces and return.
1402 return implode( ' ', $valid_class_names );
1403 }
1404 /**
1405 * Get SureForms Website URL.
1406 *
1407 * @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.
1408 * @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'].
1409 * @since 0.0.7
1410 * @return string
1411 */
1412 public static function get_sureforms_website_url( $trail, $utm_args = [] ) {
1413 $url = SRFM_WEBSITE;
1414 if ( ! empty( $trail ) && is_string( $trail ) ) {
1415 $url = SRFM_WEBSITE . $trail;
1416 }
1417
1418 if ( ! is_array( $utm_args ) ) {
1419 $utm_args = [];
1420 }
1421
1422 if ( class_exists( 'BSF_UTM_Analytics' ) ) {
1423 $url = \BSF_UTM_Analytics::get_utm_ready_link( $url, 'sureforms', $utm_args );
1424 }
1425
1426 return esc_url( $url );
1427 }
1428
1429 /**
1430 * Validates if the given string is a valid CSS class name.
1431 *
1432 * A valid CSS class name:
1433 * - Does not start with a digit, hyphen, or underscore.
1434 * - Can contain alphanumeric characters, underscores, hyphens, and Unicode letters.
1435 *
1436 * @param string $class_name The class name to validate.
1437 *
1438 * @since 1.3.1
1439 * @return bool True if the class name is valid, otherwise false.
1440 */
1441 public static function is_valid_css_class_name( $class_name ) {
1442 // Regular expression to validate a Unicode-aware CSS class name.
1443 $class_name_regex = '/^[^\d\-_][\w\p{L}\p{N}\-_]*$/u';
1444
1445 // Check if the className matches the pattern.
1446 return preg_match( $class_name_regex, $class_name ) === 1;
1447 }
1448
1449 /**
1450 * Get the gradient css for given gradient parameters.
1451 *
1452 * @param string $type The type of gradient. Default 'linear'.
1453 * @param string $color1 The first color of the gradient. Default '#FFC9B2'.
1454 * @param string $color2 The second color of the gradient. Default '#C7CBFF'.
1455 * @param int $loc1 The location of the first color. Default 0.
1456 * @param int $loc2 The location of the second color. Default 100.
1457 * @param int $angle The angle of the gradient. Default 90.
1458 *
1459 * @since 1.4.4
1460 * @return string The gradient css.
1461 */
1462 public static function get_gradient_css( $type = 'linear', $color1 = '#FFC9B2', $color2 = '#C7CBFF', $loc1 = 0, $loc2 = 100, $angle = 90 ) {
1463 if ( 'linear' === $type ) {
1464 return "linear-gradient({$angle}deg, {$color1} {$loc1}%, {$color2} {$loc2}%)";
1465 }
1466 return "radial-gradient({$color1} {$loc1}%, {$color2} {$loc2}%)";
1467 }
1468
1469 /**
1470 * Return the classes based on background and overlay type to add to the form container.
1471 *
1472 * @param string $background_type The background type.
1473 * @param string $overlay_type The overlay type.
1474 * @param string $bg_image The background image url.
1475 *
1476 * @since 1.4.4
1477 * @return string The classes to add to the form container.
1478 */
1479 public static function get_background_classes( $background_type, $overlay_type, $bg_image = '' ) {
1480 if ( empty( $background_type ) ) {
1481 $background_type = 'color';
1482 }
1483
1484 $background_type_class = '';
1485 $overlay_class = 'image' === $background_type && ! empty( $bg_image ) && $overlay_type ? "srfm-overlay-{$overlay_type}" : '';
1486
1487 // Set the class based on the background type.
1488 switch ( $background_type ) {
1489 case 'image':
1490 $background_type_class = 'srfm-bg-image';
1491 break;
1492 case 'gradient':
1493 $background_type_class = 'srfm-bg-gradient';
1494 break;
1495 default:
1496 $background_type_class = 'srfm-bg-color';
1497 break;
1498 }
1499
1500 return self::join_strings( [ $background_type_class, $overlay_class ] );
1501 }
1502
1503 /**
1504 * Custom escape function for the textarea with rich text support.
1505 *
1506 * @param string $content The content submitted by the user in the textarea block.
1507 * @since 1.7.1
1508 *
1509 * @return string Escaped content.
1510 */
1511 public static function esc_textarea( $content ) {
1512 $content = wpautop( self::sanitize_textarea( $content ) );
1513
1514 return trim( str_replace( [ "\r\n", "\r", "\n" ], '', $content ) );
1515 }
1516
1517 /**
1518 * Custom sanitization function for the textarea with rich text support.
1519 *
1520 * @param string $content The content submitted by the user in the textarea block.
1521 * @since 1.7.1
1522 *
1523 * @return string Sanitized content.
1524 */
1525 public static function sanitize_textarea( $content ) {
1526 $count = 1;
1527 $content = convert_invalid_entities( $content );
1528
1529 // Remove the 'script' and 'style' tags recursively from the content.
1530 while ( $count ) {
1531 $content = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', self::get_string_value( $content ), - 1, $count );
1532 }
1533
1534 // Disable the safe style attribute parsing for the textarea block.
1535 add_filter( 'safe_style_css', [ self::class, 'disable_style_attr_parsing' ], 10, 1 );
1536 $content = wp_kses_post( self::get_string_value( $content ) );
1537
1538 // Remove the filter after sanitization to avoid affecting other blocks.
1539 remove_filter( 'safe_style_css', [ self::class, 'disable_style_attr_parsing' ], 10 );
1540
1541 // Ensure all tags are balanced.
1542 return force_balance_tags( $content );
1543 }
1544
1545 /**
1546 * Disable parsing of style attributes for the textarea block.
1547 *
1548 * @param array<string> $allowed_styles The allowed styles.
1549 * @since 1.7.1
1550 *
1551 * @return array An empty array to disable style attribute parsing.
1552 */
1553 public static function disable_style_attr_parsing( $allowed_styles ) {
1554 unset( $allowed_styles );
1555 // Disable parsing of style attributes.
1556 return [];
1557 }
1558 /**
1559 * Strips JavaScript attributes from HTML content.
1560 *
1561 * @param string $html The HTML content to process.
1562 * @param bool $remove_link_target Optional. When true, removes target and strips noopener/noreferrer from rel on links. Default false.
1563 * @since 1.7.1
1564 * @since 2.5.2 Added $remove_link_target parameter.
1565 * @return string The cleaned HTML content without JavaScript attributes.
1566 */
1567 public static function strip_js_attributes( $html, $remove_link_target = false ) {
1568 $dom = new \DOMDocument();
1569
1570 // Suppress warnings due to malformed HTML.
1571 libxml_use_internal_errors( true );
1572 $loaded = $dom->loadHTML( '<?xml encoding="utf-8" ?>' . $html );
1573 libxml_clear_errors();
1574
1575 if ( ! $loaded ) {
1576 return $html; // Return original HTML if loading fails.
1577 }
1578
1579 $xpath = new \DOMXPath( $dom );
1580
1581 // 1. Remove all <script> tags.
1582 $script_nodes = $xpath->query( '//script' );
1583 if ( $script_nodes instanceof \DOMNodeList ) {
1584 foreach ( $script_nodes as $script ) {
1585 // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- This is a DOM element.
1586 $parent_node = $script->parentNode;
1587 if ( $parent_node instanceof \DOMNode ) {
1588 $parent_node->removeChild( $script );
1589 }
1590 }
1591 }
1592
1593 // 2. Remove all attributes that start with "on" (like onclick, onmouseover, etc.).
1594 $elements_with_on_attrs = $xpath->query( '//*[@*[starts-with(name(), "on")]]' );
1595 if ( $elements_with_on_attrs instanceof \DOMNodeList ) {
1596 foreach ( $elements_with_on_attrs as $element ) {
1597 if ( $element instanceof \DOMElement && $element->hasAttributes() ) {
1598 foreach ( iterator_to_array( $element->attributes ) as $attr ) {
1599 if ( $attr instanceof \DOMAttr && stripos( $attr->name, 'on' ) === 0 ) {
1600 $element->removeAttribute( $attr->name );
1601 }
1602 }
1603 }
1604 }
1605 }
1606
1607 // 3. Optionally remove target and target-related rel values (noopener, noreferrer) from links.
1608 if ( $remove_link_target ) {
1609 $links = $xpath->query( '//a[@target]' );
1610 if ( $links instanceof \DOMNodeList ) {
1611 foreach ( $links as $link ) {
1612 if ( $link instanceof \DOMElement ) {
1613 $link->removeAttribute( 'target' );
1614 $rel = $link->getAttribute( 'rel' );
1615 if ( $rel ) {
1616 $cleaned_rel = trim( (string) preg_replace( '/\s+/', ' ', (string) preg_replace( '/\b(noopener|noreferrer)\b/i', '', $rel ) ) );
1617 if ( $cleaned_rel ) {
1618 $link->setAttribute( 'rel', $cleaned_rel );
1619 } else {
1620 $link->removeAttribute( 'rel' );
1621 }
1622 }
1623 }
1624 }
1625 }
1626 }
1627
1628 // Return cleaned HTML.
1629 $body = $dom->getElementsByTagName( 'body' )->item( 0 );
1630 if ( $body instanceof \DOMNode ) {
1631 $cleaned_html = $dom->saveHTML( $body );
1632 return is_string( $cleaned_html ) ? $cleaned_html : '';
1633 }
1634 return '';
1635 }
1636
1637 /**
1638 * Encodes the given string with base64.
1639 * Moved from admin class to here.
1640 *
1641 * @param string $logo contains svg's.
1642 * @return string
1643 */
1644 public static function encode_svg( $logo ) {
1645 return 'data:image/svg+xml;base64,' . base64_encode( $logo ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1646 }
1647
1648 /**
1649 * Get plugin status
1650 *
1651 * @since 0.0.1
1652 * @since 1.7.0 moved to inc/helper.php from inc/admin-ajax.php
1653 *
1654 * @param string $plugin_init_file Plugin init file.
1655 * @return string
1656 */
1657 public static function get_plugin_status( $plugin_init_file ) {
1658
1659 $installed_plugins = get_plugins();
1660
1661 if ( ! isset( $installed_plugins[ $plugin_init_file ] ) ) {
1662 return 'Install';
1663 }
1664 if ( is_plugin_active( $plugin_init_file ) ) {
1665 return 'Activated';
1666 }
1667 return 'Installed';
1668 }
1669
1670 /**
1671 * Return the first installed plugin from a list, or a default if none exist.
1672 *
1673 * @since 2.0.0
1674 *
1675 * @param array<string> $plugins_to_check Plugin file paths to check, in priority order.
1676 * @param string $default Optional fallback plugin file path. Default empty string.
1677 *
1678 * @return string First installed plugin file path, or the default.
1679 */
1680 public static function get_plugin_if_installed( $plugins_to_check, $default = '' ) {
1681 if ( ! function_exists( 'get_plugins' ) ) {
1682 require_once ABSPATH . 'wp-admin/includes/plugin.php';
1683 }
1684
1685 $plugins = get_plugins();
1686
1687 foreach ( self::get_array_value( $plugins_to_check ) as $plugin_file ) {
1688 if ( isset( $plugins[ $plugin_file ] ) ) {
1689 return $plugin_file;
1690 }
1691 }
1692
1693 return $default;
1694 }
1695
1696 /**
1697 * Check which Starter Templates plugin is installed and return its main plugin file path.
1698 *
1699 * @since 1.7.3
1700 *
1701 * @return string The main plugin file path of the installed Starter Templates plugin.
1702 */
1703 public static function check_starter_template_plugin() {
1704 return self::get_plugin_if_installed(
1705 [ 'astra-pro-sites/astra-pro-sites.php' ],
1706 'astra-sites/astra-sites.php'
1707 );
1708 }
1709
1710 /**
1711 * Get sureforms recommended integrations.
1712 *
1713 * @since 0.0.1
1714 * @since 1.7.0 moved to inc/helper.php from inc/admin-ajax.php
1715 *
1716 * @return array<mixed>
1717 */
1718 public static function sureforms_get_integration() {
1719 $suretrigger_connected = apply_filters( 'suretriggers_is_user_connected', '' );
1720 $logo_sure_triggers = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suretriggers.svg' );
1721 $logo_full = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suretriggers_full.svg' );
1722 $logo_sure_mails = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suremails.svg' );
1723 $logo_uae = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/uae.svg' );
1724 $logo_starter_templates = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/starterTemplates.svg' );
1725 $logo_sure_rank = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/surerank.svg' );
1726 $logo_sure_contact = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/surecontact.svg' );
1727
1728 $integrations = [
1729 'sure_contact' => [
1730 'title' => __( 'SureContact', 'sureforms' ),
1731 'singleLineDescription' => __( 'Turn Emails Into Revenue with a CRM Built for Your Website!', 'sureforms' ),
1732 'subtitle' => __( 'Send newsletters, run campaigns, set up automations, manage contacts, and see exactly how much revenue your emails generate, all in one place.', 'sureforms' ),
1733 'status' => self::get_plugin_status( 'surecontact/surecontact.php' ),
1734 'slug' => 'surecontact',
1735 'path' => 'surecontact/surecontact.php',
1736 'logo' => self::encode_svg( is_string( $logo_sure_contact ) ? $logo_sure_contact : '' ),
1737 ],
1738 'sure_mails' => [
1739 'title' => __( 'SureMail', 'sureforms' ),
1740 'singleLineDescription' => __( 'Boost Your Email Deliverability Instantly!', 'sureforms' ),
1741 'subtitle' => __( 'Access a powerful, easy-to-use email delivery service that ensures your emails land in inboxes, not spam folders. Automate your WordPress email workflows confidently with SureMail.', 'sureforms' ),
1742 'status' => self::get_plugin_status( 'suremails/suremails.php' ),
1743 'slug' => 'suremails',
1744 'path' => 'suremails/suremails.php',
1745 'logo' => self::encode_svg( is_string( $logo_sure_mails ) ? $logo_sure_mails : '' ),
1746 ],
1747 'sure_triggers' => [
1748 'title' => __( 'OttoKit', 'sureforms' ),
1749 'singleLineDescription' => __( 'Automate your WordPress workflows effortlessly.', 'sureforms' ),
1750 'subtitle' => __( 'Connect your WordPress plugins and favourite apps, automate tasks, and sync data effortlessly using OttoKit’s clean, visual workflow builder — no coding or complex setup required.', 'sureforms' ),
1751 'status' => self::get_plugin_status( 'suretriggers/suretriggers.php' ),
1752 'slug' => 'suretriggers',
1753 'path' => 'suretriggers/suretriggers.php',
1754 'logo' => self::encode_svg( is_string( $logo_sure_triggers ) ? $logo_sure_triggers : '' ),
1755 'logo_full' => self::encode_svg( is_string( $logo_full ) ? $logo_full : '' ),
1756 'connected' => $suretrigger_connected,
1757 'connection_url' => admin_url( 'admin.php?page=suretriggers' ),
1758 ],
1759 'starter_templates' => [
1760 'title' => __( 'Starter Templates', 'sureforms' ),
1761 'singleLineDescription' => __( 'Launch Beautiful Websites in Minutes!', 'sureforms' ),
1762 'subtitle' => __( 'Choose from professionally designed templates, import with one click, and customize effortlessly to match your brand.', 'sureforms' ),
1763 'status' => self::get_plugin_status( self::check_starter_template_plugin() ),
1764 'slug' => 'astra-sites',
1765 'path' => self::check_starter_template_plugin(),
1766 'logo' => self::encode_svg( is_string( $logo_starter_templates ) ? $logo_starter_templates : '' ),
1767 ],
1768 ];
1769
1770 $elementor_installed = self::get_plugin_if_installed( [ 'elementor/elementor.php' ] );
1771
1772 if ( $elementor_installed ) {
1773 $integrations['uae'] = [
1774 'title' => __( 'Ultimate Addons for Elementor', 'sureforms' ),
1775 'singleLineDescription' => __( 'Power Up Elementor to Build Stunning Websites Faster!', 'sureforms' ),
1776 'subtitle' => __( 'Enhance Elementor with powerful widgets and templates. Build stunning, high-performing websites faster with creative design elements and seamless customization.', 'sureforms' ),
1777 'status' => self::get_plugin_status( 'header-footer-elementor/header-footer-elementor.php' ),
1778 'slug' => 'header-footer-elementor',
1779 'path' => 'header-footer-elementor/header-footer-elementor.php',
1780 'logo' => self::encode_svg( is_string( $logo_uae ) ? $logo_uae : '' ),
1781 ];
1782 } else {
1783 $integrations['sure_rank'] = [
1784 'title' => __( 'SureRank', 'sureforms' ),
1785 'singleLineDescription' => __( 'Elevate Your SEO and Climb Search Rankings Effortlessly!', 'sureforms' ),
1786 'subtitle' => __( 'Boost your website\'s visibility with smart SEO automation. Optimize content, track keyword performance, and get actionable insights, all inside WordPress.', 'sureforms' ),
1787 'status' => self::get_plugin_status( 'surerank/surerank.php' ),
1788 'slug' => 'surerank',
1789 'path' => 'surerank/surerank.php',
1790 'logo' => self::encode_svg( is_string( $logo_sure_rank ) ? $logo_sure_rank : '' ),
1791 ];
1792 }
1793
1794 return apply_filters( 'srfm_integrated_plugins', $integrations );
1795 }
1796
1797 /**
1798 * Get the current rotating plugin for the banner.
1799 *
1800 * Plugins rotate every 2 days. Only non-activated plugins are shown.
1801 * Returns false if all plugins are activated.
1802 *
1803 * @since 2.0.0
1804 * @return array<string, mixed>|false The current plugin data or false if all plugins are activated.
1805 */
1806 public static function get_rotating_plugin_banner() {
1807 $all_plugins = self::sureforms_get_integration();
1808
1809 if ( ! is_array( $all_plugins ) ) {
1810 return false;
1811 }
1812
1813 $available_plugins = [];
1814
1815 // Only include non-activated plugins.
1816 foreach ( $all_plugins as $plugin ) {
1817 if ( ! is_array( $plugin ) ) {
1818 continue;
1819 }
1820 if ( isset( $plugin['status'] ) && is_string( $plugin['status'] ) && 'Activated' !== $plugin['status'] ) {
1821 $available_plugins[] = $plugin;
1822 }
1823 }
1824
1825 // Re-index the array to have sequential numeric keys.
1826 $available_plugins = array_values( $available_plugins );
1827 $total_plugins = count( $available_plugins );
1828
1829 // Hide section if all plugins are active.
1830 if ( 0 === $total_plugins ) {
1831 return false;
1832 }
1833
1834 // Get stored rotation data.
1835 $rotation_data = self::get_srfm_option( 'plugin_banner_rotation', [] );
1836
1837 if ( ! is_array( $rotation_data ) ) {
1838 $rotation_data = [];
1839 }
1840
1841 // Initialize rotation data if empty.
1842 if ( empty( $rotation_data ) ) {
1843 $current_time = time();
1844 self::update_srfm_option(
1845 'plugin_banner_rotation',
1846 [
1847 'last_rotation_date' => $current_time,
1848 'plugin_index' => 0,
1849 ]
1850 );
1851 return isset( $available_plugins[0] ) && is_array( $available_plugins[0] ) ? $available_plugins[0] : false;
1852 }
1853
1854 $last_rotation_date = isset( $rotation_data['last_rotation_date'] ) && is_int( $rotation_data['last_rotation_date'] ) ? $rotation_data['last_rotation_date'] : 0;
1855 $plugin_index = isset( $rotation_data['plugin_index'] ) && is_numeric( $rotation_data['plugin_index'] ) ? intval( $rotation_data['plugin_index'] ) : 0;
1856
1857 $current_time = time();
1858 $days_since_rotation = ( $current_time - $last_rotation_date ) / DAY_IN_SECONDS;
1859
1860 // Rotate every 2 days.
1861 if ( $days_since_rotation >= 2 ) {
1862 // Rotate to next plugin.
1863 ++$plugin_index;
1864 $plugin_index %= $total_plugins;
1865
1866 // Update the rotation data.
1867 self::update_srfm_option(
1868 'plugin_banner_rotation',
1869 [
1870 'last_rotation_date' => $current_time,
1871 'plugin_index' => $plugin_index,
1872 ]
1873 );
1874 }
1875
1876 // Ensure the index is within bounds.
1877 if ( $plugin_index >= $total_plugins ) {
1878 $plugin_index = 0;
1879 }
1880
1881 return isset( $available_plugins[ $plugin_index ] ) && is_array( $available_plugins[ $plugin_index ] ) ? $available_plugins[ $plugin_index ] : false;
1882 }
1883
1884 /**
1885 * Get a value from the srfm_options array.
1886 *
1887 * @param string $key The key to retrieve.
1888 * @param mixed $default The default value to return if the key does not exist.
1889 * @since 1.8.0
1890 * @return mixed
1891 */
1892 public static function get_srfm_option( $key, $default = null ) {
1893 $options = get_option( 'srfm_options', [] );
1894 if ( ! is_array( $options ) ) {
1895 $options = [];
1896 }
1897 return array_key_exists( $key, $options ) ? $options[ $key ] : $default;
1898 }
1899
1900 /**
1901 * Update a value in the srfm_options array.
1902 *
1903 * @param string $key The key to update.
1904 * @param mixed $value The value to set.
1905 * @since 1.8.0
1906 * @return void
1907 */
1908 public static function update_srfm_option( $key, $value ) {
1909 $options = get_option( 'srfm_options', [] );
1910 if ( ! is_array( $options ) ) {
1911 $options = [];
1912 }
1913 $options[ $key ] = $value;
1914 update_option( 'srfm_options', $options );
1915 }
1916
1917 /**
1918 * Get the WordPress file types.
1919 *
1920 * @since 1.7.4
1921 * @return array<string,mixed> An associative array representing the file types.
1922 */
1923 public static function get_wp_file_types() {
1924 $formats = [];
1925 $mimes = get_allowed_mime_types();
1926 $maxsize = wp_max_upload_size() / 1048576;
1927 if ( ! empty( $mimes ) ) {
1928 foreach ( $mimes as $type => $mime ) {
1929 $multiple = explode( '|', $type );
1930 foreach ( $multiple as $single ) {
1931 $formats[] = $single;
1932 }
1933 }
1934 }
1935
1936 return [
1937 'formats' => $formats,
1938 'maxsize' => $maxsize,
1939 ];
1940 }
1941
1942 /**
1943 * Determines if the SureForms Pro plugin is installed and active.
1944 *
1945 * Checks for the presence of the SRFM_PRO_VER constant.
1946 *
1947 * @since 1.8.0
1948 *
1949 * @return bool True if the Pro plugin is active; false otherwise.
1950 */
1951 public static function has_pro() {
1952 return defined( 'SRFM_PRO_VER' );
1953 }
1954
1955 /**
1956 * Verifies the request by checking the nonce and user capabilities.
1957 *
1958 * @param string $request_type The type of request, either 'rest' or 'ajax'.
1959 * @param string $nonce_action The action name for the nonce.
1960 * @param string $nonce_name The name of the nonce field.
1961 * @param string $capability The capability required to perform the action. Default is 'manage_options'.
1962 *
1963 * @since 1.10.0
1964 * @return void
1965 */
1966 public static function verify_nonce_and_capabilities( $request_type, $nonce_action, $nonce_name, $capability = 'manage_options' ) {
1967
1968 if ( ! is_string( $nonce_action ) || ! is_string( $nonce_name ) || empty( $nonce_action ) || empty( $nonce_name ) ) {
1969 wp_send_json_error(
1970 [ 'message' => __( 'Invalid nonce action or name.', 'sureforms' ) ],
1971 400
1972 );
1973 }
1974
1975 // Verify nonce for security.
1976 if ( 'rest' === $request_type ) {
1977 // For REST API requests, use the WP_REST_Request object to verify the nonce.
1978 if ( ! wp_verify_nonce( $nonce_action, $nonce_name ) ) {
1979 wp_send_json_error(
1980 [ 'message' => __( 'Invalid security token.', 'sureforms' ) ],
1981 403
1982 );
1983 }
1984 } elseif ( 'ajax' === $request_type ) {
1985 // For non-REST requests, use the standard nonce verification.
1986 if ( ! check_ajax_referer( $nonce_action, $nonce_name, false ) ) {
1987 wp_send_json_error(
1988 [ 'message' => __( 'Invalid security token.', 'sureforms' ) ],
1989 403
1990 );
1991 }
1992 } else {
1993 // If the request type is not recognized, return an error.
1994 wp_send_json_error(
1995 [ 'message' => __( 'Invalid request type.', 'sureforms' ) ],
1996 400
1997 );
1998 }
1999
2000 // Check user capabilities.
2001 if ( ! current_user_can( $capability ) ) {
2002 wp_send_json_error(
2003 [ 'message' => esc_html__( 'You do not have permission to perform this action.', 'sureforms' ) ],
2004 403
2005 );
2006 }
2007 }
2008
2009 /**
2010 * Get the block name from a field name by extracting the first two parts.
2011 *
2012 * @param string $field_name The full field name (e.g., 'srfm-text-lbl-123').
2013 *
2014 * @since 1.11.0
2015 * @return string The block name (e.g., 'srfm-text').
2016 */
2017 public static function get_block_name_from_field( $field_name ) {
2018 return implode( '-', array_slice( explode( '-', explode( '-lbl-', $field_name )[0] ), 0, 2 ) );
2019 }
2020
2021 /**
2022 * Check if any of the top 10 popular WordPress SMTP plugins is active using array_intersect.
2023 *
2024 * @since 1.9.1
2025 * @return bool True if any SMTP plugin is active, false otherwise.
2026 */
2027 public static function is_any_smtp_plugin_active() {
2028 $smtp_plugins = [
2029 'wp-mail-smtp/wp_mail_smtp.php',
2030 'post-smtp/postman-smtp.php',
2031 'easy-wp-smtp/easy-wp-smtp.php',
2032 'wp-smtp/wp-smtp.php',
2033 'newsletter/plugin.php',
2034 'fluent-smtp/fluent-smtp.php',
2035 'pepipost-smtp/pepipost-smtp.php',
2036 'mail-bank/wp-mail-bank.php',
2037 'smtp-mailer/smtp-mailer.php',
2038 'suremails/suremails.php',
2039 'site-mailer/site-mailer.php',
2040 ];
2041
2042 $active_plugins = (array) get_option( 'active_plugins', [] );
2043 // For multisite, merge sitewide active plugins.
2044 if ( is_multisite() ) {
2045 $network_plugins = (array) get_site_option( 'active_sitewide_plugins', [] );
2046 $active_plugins = array_merge( $active_plugins, array_keys( $network_plugins ) );
2047 }
2048
2049 return (bool) array_intersect( $smtp_plugins, $active_plugins );
2050 }
2051
2052 /**
2053 * Apply a filter and return the filtered value only if it's a non-empty array.
2054 * Otherwise, return the default array.
2055 *
2056 * @param string $filter_name The name of the filter to apply.
2057 * @param mixed $default The default array to return if the filtered result is invalid.
2058 * @param mixed ...$args Additional arguments to pass to the filter.
2059 *
2060 * @return array The filtered array if valid, otherwise the default.
2061 */
2062 public static function apply_filters_as_array( $filter_name, $default, ...$args ) {
2063 // Ensure $default is an array.
2064 if ( ! is_array( $default ) ) {
2065 $default = [];
2066 }
2067
2068 // Validate the filter name.
2069 if ( ! is_string( $filter_name ) || empty( $filter_name ) ) {
2070 return $default;
2071 }
2072
2073 // Apply the filter with additional arguments.
2074 $filtered = apply_filters( $filter_name, $default, ...$args );
2075
2076 // Return filtered result if it's a non-empty array.
2077 return is_array( $filtered ) && ! empty( $filtered ) ? $filtered : $default;
2078 }
2079
2080 /**
2081 * Get forms with entry counts for a specific time period.
2082 *
2083 * @param int $timestamp The timestamp to get entries after.
2084 * @param int $limit Maximum number of forms to return (0 for all).
2085 * @param bool $sort Whether to sort by entry count descending.
2086 * @return array Array of form data with entry counts.
2087 * @since 1.9.1
2088 */
2089 public static function get_forms_with_entry_counts( $timestamp, $limit = 0, $sort = true ) {
2090 // Get all published forms with post objects for bulk title access.
2091 $args = [
2092 'post_type' => SRFM_FORMS_POST_TYPE,
2093 'posts_per_page' => -1,
2094 'post_status' => 'publish',
2095 'orderby' => 'ID',
2096 'order' => 'DESC',
2097 'no_found_rows' => true,
2098 'update_post_term_cache' => false,
2099 'update_post_meta_cache' => false,
2100 ];
2101
2102 $query = new \WP_Query( $args );
2103
2104 if ( ! $query->have_posts() ) {
2105 return [];
2106 }
2107
2108 $all_forms = [];
2109
2110 // Process posts directly from the query results without touching global $post.
2111 foreach ( $query->posts as $form ) {
2112 // Ensure we have a valid post object.
2113 if ( ! $form instanceof \WP_Post ) {
2114 continue;
2115 }
2116
2117 $form_id = (int) $form->ID;
2118 if ( $form_id <= 0 ) {
2119 continue;
2120 }
2121
2122 // Get entries count after the timestamp for this specific form.
2123 $entry_count = Entries::get_entries_count_after( $timestamp, $form_id );
2124
2125 // Get form title directly from post object, use "Blank Form" if empty.
2126 $form_title = $form->post_title;
2127 if ( empty( trim( self::get_string_value( $form_title ) ) ) ) {
2128 $form_title = __( 'Blank Form', 'sureforms' );
2129 }
2130
2131 $all_forms[] = [
2132 'form_id' => $form_id,
2133 'title' => $form_title,
2134 'count' => $entry_count,
2135 ];
2136 }
2137
2138 // Sort by count descending, then by form_id descending for consistency.
2139 if ( $sort ) {
2140 usort(
2141 $all_forms,
2142 static function( $a, $b ) {
2143 if ( $a['count'] === $b['count'] ) {
2144 return $b['form_id'] - $a['form_id'];
2145 }
2146 return $b['count'] - $a['count'];
2147 }
2148 );
2149 }
2150
2151 // Return limited results if specified.
2152 if ( $limit > 0 ) {
2153 return array_slice( $all_forms, 0, $limit );
2154 }
2155
2156 return $all_forms;
2157 }
2158
2159 /**
2160 * Check if the given form ID is valid SureForms form ID.
2161 * A valid form ID is a numeric value that corresponds to an existing SureForms form in the database.
2162 *
2163 * @since 1.9.1
2164 *
2165 * @param int|string|mixed $form_id The form ID to validate.
2166 * @return bool True if the form ID is valid, false otherwise.
2167 */
2168 public static function is_valid_form( $form_id ) {
2169
2170 // Check for a valid form ID.
2171 if ( empty( $form_id ) || ! is_numeric( $form_id ) ) {
2172 return false;
2173 }
2174
2175 // Check if the form ID exists in the database.
2176 $form = get_post( self::get_integer_value( $form_id ) );
2177
2178 // If the form does not exist or is not of the correct post type, return false.
2179 if ( ! $form || ! is_a( $form, 'WP_Post' ) || SRFM_FORMS_POST_TYPE !== $form->post_type ) {
2180 return false;
2181 }
2182
2183 return true;
2184 }
2185
2186 /**
2187 * Get the timestamp from a string.
2188 *
2189 * This function uses WordPress's configured timezone (from Settings → General → Timezone)
2190 * to ensure consistent behavior regardless of the server's timezone settings.
2191 *
2192 * @param string $date The date in YYYY-MM-DD format (e.g., '2026-01-10').
2193 * @param string $hours The hours in 12-hour format (e.g., '12', '01'-'12').
2194 * @param string $minutes The minutes (e.g., '00', '00'-'59').
2195 * @param string $meridiem The meridiem (e.g., 'AM' or 'PM').
2196 *
2197 * @since 1.10.1
2198 * @return int|false The timestamp if successful, false otherwise.
2199 */
2200 public static function get_timestamp_from_string( $date, $hours = '12', $minutes = '00', $meridiem = 'AM' ) {
2201
2202 if ( empty( $date ) || ! is_string( $date ) ) {
2203 return false; // Invalid input.
2204 }
2205
2206 // Ensure the date is in a valid format of YYYY-MM-DD.
2207 if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $date ) ) {
2208 return false; // Invalid date format.
2209 }
2210
2211 $time_string = $date . ' ' . $hours . ':' . $minutes . ' ' . $meridiem;
2212
2213 // Convert to timestamp using WordPress timezone.
2214 // This ensures the date/time is interpreted in the site's configured timezone,
2215 // not the server's timezone or PHP's default timezone.
2216 try {
2217 $datetime = date_create( $time_string, wp_timezone() );
2218
2219 if ( false === $datetime ) {
2220 return false;
2221 }
2222
2223 $timestamp = $datetime->getTimestamp();
2224
2225 if ( is_int( $timestamp ) && $timestamp > 0 ) {
2226 return $timestamp;
2227 }
2228 } catch ( \Exception $e ) {
2229 // If timezone conversion fails, return false.
2230 return false;
2231 }
2232
2233 // If conversion fails, return false.
2234 return false;
2235 }
2236
2237 /**
2238 * Generate a unique ID for the saved form.
2239 * Also ensures that the generated ID does not already exist in the database table.
2240 *
2241 * @param class-string $class The class name where the get method is defined to check for existing IDs.
2242 * @param int<1, max> $length The length of the random bytes to generate. Default is 8.
2243 * @return string
2244 * @since 2.2.0
2245 */
2246 public static function generate_unique_id( $class, $length = 8 ) {
2247 // Ensure length is at least 1.
2248 $length = max( 1, $length );
2249
2250 do {
2251 $id = bin2hex( random_bytes( $length ) );
2252 } while ( is_callable( [ $class, 'get' ] ) && call_user_func( [ $class, 'get' ], $id ) );
2253 return $id;
2254 }
2255
2256 /**
2257 * Log error messages to the error log.
2258 *
2259 * This function checks if error_log function exists, validates the message,
2260 * and logs it with the print_r second argument set to true.
2261 *
2262 * Logging is disabled by default. To enable logging, add this to wp-config.php:
2263 * define( 'SRFM_LOG', true );
2264 *
2265 * @param mixed $message The error message to log. Can be string or any type.
2266 * @param string $prefix Optional prefix to add before the message. Default: 'Log :'.
2267 *
2268 * @since 2.0.0
2269 * @return void
2270 */
2271 public static function srfm_log( $message, $prefix = 'Log :' ) {
2272 // Check if logging is enabled via SRFM_LOG constant.
2273 if ( ! defined( 'SRFM_LOG' ) ) {
2274 return;
2275 }
2276 unset( $message, $prefix );
2277 }
2278
2279 /**
2280 * Encodes data to base64 after JSON encoding with validation.
2281 *
2282 * This function checks if the data is non-empty and valid for JSON encoding.
2283 * If data is not valid, returns an empty string.
2284 * Otherwise, it attempts to JSON encode and then base64 encode the result.
2285 *
2286 * @param mixed $data The data to JSON encode and then base64 encode.
2287 * @return string The base64-encoded JSON string, or empty string on failure.
2288 */
2289 public static function srfm_base64_json_encode( $data ) {
2290 if ( empty( $data ) || ! is_array( $data ) ) {
2291 return '';
2292 }
2293
2294 $json = wp_json_encode( $data );
2295 if ( false === $json || '' === $json ) {
2296 return '';
2297 }
2298
2299 // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2300 return base64_encode( $json );
2301 }
2302
2303 }
2304