PluginProbe
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz / 2.7.1
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz v2.7.1
2.12.6 2.12.5 2.12.4 2.12.3 2.12.2 2.12.1 2.12.0 2.11.1 2.11.0 2.10.1 2.10.0 2.9.1 2.9.0 2.8.2 2.8.1 2.7.0 2.7.1 2.8.0 trunk 0.0.10 0.0.11 0.0.12 0.0.13 0.0.2 0.0.3 All 96 releases
sureforms / inc / helper.php
helper.php
2,316 lines 79.2 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 $slug = str_replace( ' ', '_', $slug );
744
745 /**
746 * Filters whether a field should be skipped when mapping slugs to submission data.
747 *
748 * This filter allows plugins or custom code to determine if a field should be excluded
749 * from the mapped submission data array (such as for internal fields or extraneous meta).
750 *
751 * @since 2.0.0
752 *
753 * @param bool $skip_this_field Whether to skip this field from processing. Default false.
754 * @param array $args {
755 * Arguments used for this field.
756 *
757 * @type string $key The original key of the field in the submission data array.
758 * @type string $slug The mapped slug parsed from the field key.
759 * @type mixed $value The value assigned to this field.
760 * }
761 */
762 $skip_this_field = apply_filters(
763 'srfm_map_slug_to_submission_data_should_skip',
764 false,
765 [
766 'key' => $key,
767 'slug' => $slug,
768 'value' => $value,
769 ]
770 );
771
772 if ( $skip_this_field ) {
773 continue;
774 }
775
776 // Check if value is array to handle external package field functionality.
777 // like repeater fields that need special processing.
778 if ( is_array( $value ) && ! empty( $value ) ) {
779 // Apply filter to allow external packages to process array values.
780 // Returns processed data with 'is_processed' flag if successfully handled.
781 $filtered_submission_data = apply_filters(
782 'srfm_map_slug_to_submission_data_array',
783 [
784 'value' => $value,
785 'key' => $key,
786 'slug' => $slug,
787 ]
788 );
789 if ( isset( $filtered_submission_data['is_processed'] ) && true === $filtered_submission_data['is_processed'] ) {
790 $mapped_data[ $slug ] = $filtered_submission_data['value'];
791 continue;
792 }
793 }
794
795 // If the value is an array (e.g. multi-upload field), decode each URL value.
796 if ( is_array( $value ) ) {
797 $mapped_data[ $slug ] = array_map(
798 static function ( $val ) {
799 return is_string( $val ) ? rawurldecode( $val ) : $val;
800 },
801 $value
802 );
803 continue;
804 }
805
806 $mapped_data[ $slug ] = is_string( $value ) ? html_entity_decode( esc_attr( $value ) ) : $value;
807 }
808 return $mapped_data;
809 }
810
811 /**
812 * Get forms options. Shows all the available forms in the dropdown.
813 *
814 * @since 0.0.5
815 * @param string $key Determines the type of data to return.
816 * @return array<mixed>
817 */
818 public static function get_sureforms( $key = '' ) {
819 $forms = get_posts(
820 apply_filters(
821 'srfm_get_sureforms_query_args',
822 [
823 'post_type' => SRFM_FORMS_POST_TYPE,
824 'posts_per_page' => -1,
825 'post_status' => 'publish',
826 ]
827 )
828 );
829
830 $options = [];
831
832 foreach ( $forms as $form ) {
833 if ( $form instanceof WP_Post ) {
834 if ( 'all' === $key ) {
835 $options[ $form->ID ] = $form;
836 } elseif ( ! empty( $key ) && is_string( $key ) && isset( $form->$key ) ) {
837 $options[ $form->ID ] = $form->$key;
838 } else {
839 $options[ $form->ID ] = $form->post_title;
840 }
841 }
842 }
843
844 return $options;
845 }
846
847 /**
848 * Get all the forms.
849 *
850 * @since 0.0.5
851 * @return array<mixed>
852 */
853 public static function get_sureforms_title_with_ids() {
854 $form_options = self::get_sureforms();
855
856 foreach ( $form_options as $key => $value ) {
857 $form_options[ $key ] = $value . ' #' . $key;
858 }
859
860 return $form_options;
861 }
862
863 /**
864 * Get the CSS variables based on different field spacing sizes.
865 *
866 * @param string|null $field_spacing The field spacing size or boolean false to return complete sizes array.
867 *
868 * @since 0.0.7
869 * @return array<string|mixed>
870 */
871 public static function get_css_vars( $field_spacing = null ) {
872 /**
873 * $sizes - Field Spacing Sizes Variables.
874 * The array contains the CSS variables for different field spacing sizes.
875 * Each key corresponds to the field spacing size, and the value is an array of CSS variables.
876 *
877 * For future variables depending on the field spacing size, add the variable to the array respectively.
878 */
879 $sizes = apply_filters(
880 'srfm_css_vars_sizes',
881 [
882 'small' => [
883 '--srfm-row-gap-between-blocks' => '16px',
884 // Address block gap and spacing variables.
885 '--srfm-address-label-font-size' => '14px',
886 '--srfm-address-label-line-height' => '20px',
887 '--srfm-address-description-font-size' => '12px',
888 '--srfm-address-description-line-height' => '16px',
889 '--srfm-col-gap-between-fields' => '12px',
890 '--srfm-row-gap-between-fields' => '12px',
891 '--srfm-gap-below-address-label' => '12px',
892 // Dropdown Variables.
893 '--srfm-dropdown-font-size' => '14px',
894 '--srfm-dropdown-gap-between-input-menu' => '4px',
895 '--srfm-dropdown-badge-padding' => '2px 6px',
896 '--srfm-dropdown-multiselect-font-size' => '12px',
897 '--srfm-dropdown-multiselect-line-height' => '16px',
898 '--srfm-dropdown-padding-right' => '12px',
899 // initial padding and from 20px - 12px for dropdown arrow width and 8px for gap before dropdown arrow.
900 '--srfm-dropdown-padding-right-icon' => 'calc( var( --srfm-dropdown-padding-right ) + 20px )',
901 '--srfm-dropdown-multiselect-padding' => '8px var( --srfm-dropdown-padding-right-icon ) 8px 8px',
902 // Input Field Variables.
903 '--srfm-input-height' => '40px',
904 '--srfm-input-field-padding' => '10px 12px',
905 '--srfm-input-field-font-size' => '14px',
906 '--srfm-input-field-line-height' => '20px',
907 '--srfm-input-field-margin-top' => '4px',
908 '--srfm-input-field-margin-bottom' => '4px',
909 // Checkbox and GDPR Variables.
910 '--srfm-checkbox-label-font-size' => '14px',
911 '--srfm-checkbox-label-line-height' => '20px',
912 '--srfm-checkbox-description-font-size' => '12px',
913 '--srfm-checkbox-description-line-height' => '16px',
914 '--srfm-check-ctn-width' => '16px',
915 '--srfm-check-ctn-height' => '16px',
916 '--srfm-check-svg-size' => '10px',
917 '--srfm-checkbox-margin-top-frontend' => '2px',
918 '--srfm-checkbox-margin-top-editor' => '3px',
919 '--srfm-check-gap' => '8px',
920 '--srfm-checkbox-description-margin-left' => '24px',
921 // Phone Number field variables.
922 '--srfm-flag-section-padding' => '10px 0 10px 12px',
923 '--srfm-gap-between-icon-text' => '8px',
924 // Label Variables.
925 '--srfm-label-font-size' => '14px',
926 '--srfm-label-line-height' => '20px',
927 // Description Variables.
928 '--srfm-description-font-size' => '12px',
929 '--srfm-description-line-height' => '16px',
930 // Button Variables.
931 '--srfm-btn-padding' => '8px 14px',
932 '--srfm-btn-font-size' => '14px',
933 '--srfm-btn-line-height' => '20px',
934 // Multi Choice Variables.
935 '--srfm-multi-choice-horizontal-padding' => '16px',
936 '--srfm-multi-choice-vertical-padding' => '16px',
937 '--srfm-multi-choice-internal-option-gap' => '8px',
938 '--srfm-multi-choice-vertical-svg-size' => '32px',
939 '--srfm-multi-choice-horizontal-image-size' => '20px',
940 '--srfm-multi-choice-vertical-image-size' => '100px',
941 '--srfm-multi-choice-outer-padding' => '0',
942 ],
943 'medium' => [
944 '--srfm-row-gap-between-blocks' => '18px',
945 // Address block gap and spacing variables.
946 '--srfm-address-label-font-size' => '16px',
947 '--srfm-address-label-line-height' => '24px',
948 '--srfm-address-description-font-size' => '14px',
949 '--srfm-address-description-line-height' => '20px',
950 '--srfm-col-gap-between-fields' => '16px',
951 '--srfm-row-gap-between-fields' => '16px',
952 '--srfm-gap-below-address-label' => '14px',
953 // Input Field Variables.
954 '--srfm-input-height' => '44px',
955 '--srfm-input-field-font-size' => '16px',
956 '--srfm-input-field-line-height' => '24px',
957 '--srfm-input-field-margin-top' => '6px',
958 '--srfm-input-field-margin-bottom' => '6px',
959 // Checkbox and GDPR Variables.
960 '--srfm-checkbox-label-font-size' => '16px',
961 '--srfm-checkbox-label-line-height' => '24px',
962 '--srfm-checkbox-description-font-size' => '14px',
963 '--srfm-checkbox-description-line-height' => '20px',
964 '--srfm-checkbox-margin-top-frontend' => '4px',
965 '--srfm-checkbox-margin-top-editor' => '6px',
966 '--srfm-checkbox-description-margin-left' => '24px',
967 // Label Variables.
968 '--srfm-label-font-size' => '16px',
969 '--srfm-label-line-height' => '24px',
970 // Description Variables.
971 '--srfm-description-font-size' => '14px',
972 '--srfm-description-line-height' => '20px',
973 // Button Variables.
974 '--srfm-btn-padding' => '10px 14px',
975 '--srfm-btn-font-size' => '16px',
976 '--srfm-btn-line-height' => '24px',
977 // Multi Choice Variables.
978 '--srfm-multi-choice-horizontal-padding' => '20px',
979 '--srfm-multi-choice-vertical-padding' => '20px',
980 '--srfm-multi-choice-vertical-svg-size' => '40px',
981 '--srfm-multi-choice-horizontal-image-size' => '24px',
982 '--srfm-multi-choice-vertical-image-size' => '120px',
983 '--srfm-multi-choice-outer-padding' => '2px',
984 ],
985 'large' => [
986 '--srfm-row-gap-between-blocks' => '20px',
987 // Address Block Gap and Spacing Variables.
988 '--srfm-address-label-font-size' => '18px',
989 '--srfm-address-label-line-height' => '28px',
990 '--srfm-address-description-font-size' => '16px',
991 '--srfm-address-description-line-height' => '24px',
992 '--srfm-col-gap-between-fields' => '16px',
993 '--srfm-row-gap-between-fields' => '20px',
994 '--srfm-gap-below-address-label' => '16px',
995 // Dropdown Variables.
996 '--srfm-dropdown-font-size' => '16px',
997 '--srfm-dropdown-gap-between-input-menu' => '6px',
998 '--srfm-dropdown-badge-padding' => '6px 6px',
999 '--srfm-dropdown-multiselect-font-size' => '14px',
1000 '--srfm-dropdown-multiselect-line-height' => '20px',
1001 '--srfm-dropdown-padding-right' => '14px',
1002 // Input Field Variables.
1003 '--srfm-input-height' => '48px',
1004 '--srfm-input-field-padding' => '10px 14px',
1005 '--srfm-input-field-font-size' => '18px',
1006 '--srfm-input-field-line-height' => '28px',
1007 '--srfm-input-field-margin-top' => '8px',
1008 '--srfm-input-field-margin-bottom' => '8px',
1009 // Checkbox and GDPR Variables.
1010 '--srfm-checkbox-label-font-size' => '18px',
1011 '--srfm-checkbox-label-line-height' => '28px',
1012 '--srfm-checkbox-description-font-size' => '16px',
1013 '--srfm-checkbox-description-line-height' => '24px',
1014 '--srfm-check-ctn-width' => '20px',
1015 '--srfm-check-ctn-height' => '20px',
1016 '--srfm-check-svg-size' => '14px',
1017 '--srfm-check-gap' => '10px',
1018 '--srfm-checkbox-margin-top-frontend' => '4px',
1019 '--srfm-checkbox-margin-top-editor' => '5px',
1020 '--srfm-checkbox-description-margin-left' => '30px',
1021 // Label Variables.
1022 '--srfm-label-font-size' => '18px',
1023 '--srfm-label-line-height' => '28px',
1024 // Description Variables.
1025 '--srfm-description-font-size' => '16px',
1026 '--srfm-description-line-height' => '24px',
1027 // Button Variables.
1028 '--srfm-btn-padding' => '10px 14px',
1029 '--srfm-btn-font-size' => '18px',
1030 '--srfm-btn-line-height' => '28px',
1031 // Multi Choice Variables.
1032 '--srfm-multi-choice-horizontal-padding' => '24px',
1033 '--srfm-multi-choice-vertical-padding' => '24px',
1034 '--srfm-multi-choice-internal-option-gap' => '12px',
1035 '--srfm-multi-choice-vertical-svg-size' => '48px',
1036 '--srfm-multi-choice-horizontal-image-size' => '28px',
1037 '--srfm-multi-choice-vertical-image-size' => '140px',
1038 '--srfm-multi-choice-outer-padding' => '4px',
1039 ],
1040 ]
1041 );
1042 // Return complete sizes array if field_spacing is false. Required in case of JS for Editor changes.
1043 if ( ! $field_spacing ) {
1044 return $sizes;
1045 }
1046
1047 $selected_size = $sizes['small'];
1048 if ( 'small' !== $field_spacing && isset( $sizes[ $field_spacing ] ) ) {
1049 $selected_size = array_merge( $selected_size, $sizes[ $field_spacing ] );
1050 }
1051
1052 return $selected_size;
1053 }
1054
1055 /**
1056 * Array of SureForms blocks which get have user input.
1057 *
1058 * @since 0.0.10
1059 * @return array<string>
1060 */
1061 public static function get_sureforms_blocks() {
1062 return apply_filters(
1063 'srfm_blocks',
1064 [
1065 'srfm/input',
1066 'srfm/email',
1067 'srfm/textarea',
1068 'srfm/number',
1069 'srfm/checkbox',
1070 'srfm/gdpr',
1071 'srfm/phone',
1072 'srfm/address',
1073 'srfm/dropdown',
1074 'srfm/multi-choice',
1075 'srfm/radio',
1076 'srfm/submit',
1077 'srfm/url',
1078 'srfm/payment',
1079 ]
1080 );
1081 }
1082
1083 /**
1084 * Render a site key missing error message.
1085 *
1086 * @param string $provider_name Name of the captcha provider (e.g., HCaptcha, Google reCAPTCHA, Turnstile).
1087 * @since 1.7.0
1088 * @since 1.7.1 moved to inc/helper.php from inc/generate-form-markup.php
1089 * @return void
1090 */
1091 public static function render_missing_sitekey_error( $provider_name ) {
1092 $icon = self::fetch_svg( 'info_circle', '', 'aria-hidden="true"' );
1093 ?>
1094 <p id="sitekey-error" class="srfm-common-error-message srfm-error-message">
1095 <?php echo wp_kses( $icon, self::$allowed_tags_svg ); ?>
1096 <span class="srfm-error-content">
1097 <?php
1098 echo esc_html(
1099 sprintf(
1100 /* translators: %s: Provider name like HCaptcha, Google reCAPTCHA, Turnstile */
1101 __( '%s sitekey is missing. Please contact your site administrator.', 'sureforms' ),
1102 $provider_name
1103 )
1104 );
1105 ?>
1106 </span>
1107 </p>
1108 <?php
1109 }
1110
1111 /**
1112 * Parse and sanitize an email list string which may contain:
1113 *
1114 * @param string $input email addresses.
1115 * @since 1.13.2
1116 * @return string Sanitized email header string.
1117 */
1118 public static function sanitize_email_header( $input ) {
1119 if ( empty( $input ) ) {
1120 return '';
1121 }
1122
1123 $parts = explode( ',', $input );
1124 $output = [];
1125
1126 foreach ( $parts as $part ) {
1127 $part = trim( $part );
1128
1129 // Match "Name <email>".
1130 if ( preg_match( '/^(.*)<(.+)>$/', $part, $matches ) ) {
1131 $name = trim( $matches[1], "\" \t\n\r\0\x0B" ); // trim quotes.
1132 $email = sanitize_email( trim( $matches[2] ) );
1133
1134 if ( is_email( $email ) ) {
1135 $safe_name = sanitize_text_field( $name );
1136 $output[] = $safe_name . ' <' . $email . '>';
1137 }
1138 } else {
1139 // Plain email case.
1140 $email = sanitize_email( $part );
1141 if ( is_email( $email ) ) {
1142 $output[] = $email;
1143 }
1144 }
1145 }
1146
1147 return ! empty( $output ) ? implode( ', ', $output ) : '';
1148 }
1149
1150 /**
1151 * Process blocks and inner blocks.
1152 *
1153 * @param array<mixed> $blocks The block data.
1154 * @param array<string> $slugs The array of existing slugs.
1155 * @param bool $updated The array of existing slugs.
1156 * @param string $prefix The array of existing slugs.
1157 * @param bool $skip_checking_existing_slug Skips the checking of existing slug if passed true. More information documented inside this function.
1158 * @since 0.0.10
1159 * @return array
1160 */
1161 public static function process_blocks( $blocks, &$slugs, &$updated, $prefix = '', $skip_checking_existing_slug = false ) {
1162
1163 if ( ! is_array( $blocks ) ) {
1164 return [ $blocks, $slugs, $updated ];
1165 }
1166
1167 foreach ( $blocks as $index => $block ) {
1168
1169 if ( ! is_array( $block ) ) {
1170 continue;
1171 }
1172 // Checking only for SureForms blocks which can have user input.
1173 if ( empty( $block['blockName'] ) || ! in_array( $block['blockName'], self::get_sureforms_blocks(), true ) ) {
1174 continue;
1175 }
1176
1177 /**
1178 * Lets continue if slug already exists.
1179 * This will ensure that we don't update already existing slugs.
1180 */
1181 if ( isset( $block['attrs'] ) && ! empty( $block['attrs']['slug'] ) && ! in_array( $block['attrs']['slug'], $slugs, true ) ) {
1182
1183 // Made it associative array, so that we can directly check it using block_id rather than mapping or using "in_array" for the checks.
1184 $slugs[ $block['attrs']['block_id'] ] = self::get_string_value( $block['attrs']['slug'] );
1185
1186 if ( is_array( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) ) {
1187 [ $blocks[ $index ]['innerBlocks'], $slugs, $updated ] = self::process_blocks( $block['innerBlocks'], $slugs, $updated, '' );
1188 }
1189 continue;
1190 }
1191
1192 if ( $skip_checking_existing_slug && empty( $block['innerBlocks'] ) && isset( $slugs[ $block['attrs']['block_id'] ] ) ) {
1193 /**
1194 * Skip re-processing of the already process or existing slugs if above parameter "$skip_checking_existing_slug" is passed as true.
1195 * This is helpful in the scenarios where we need to compare and verify between already saved blocks and new unsaved blocks parsed
1196 * from the contents.
1197 *
1198 * However, it is also necessary to make sure if that current block is not a parent / wrapper block
1199 * by checking "$block['innerBlocks']" empty.
1200 *
1201 * And finally, checking if the block-id "$block['attrs']['block_id']" is already set in the list of "$slugs",
1202 * making sure that we are only processing the new blocks.
1203 */
1204 continue;
1205 }
1206
1207 if ( is_array( $blocks[ $index ]['attrs'] ) ) {
1208
1209 $blocks[ $index ]['attrs']['slug'] = self::generate_unique_block_slug( $block, $slugs, $prefix );
1210 $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.
1211 $updated = true;
1212 if ( is_array( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) ) {
1213
1214 [ $blocks[ $index ]['innerBlocks'], $slugs, $updated ] = self::process_blocks( $block['innerBlocks'], $slugs, $updated, $blocks[ $index ]['attrs']['slug'] );
1215
1216 }
1217 }
1218 }
1219 return [ $blocks, $slugs, $updated ];
1220 }
1221
1222 /**
1223 * Generates slug based on the provided block and existing slugs.
1224 *
1225 * @param array<mixed> $block The block data.
1226 * @param array<string> $slugs The array of existing slugs.
1227 * @param string $prefix The array of existing slugs.
1228 * @since 0.0.10
1229 * @return string The generated unique block slug.
1230 */
1231 public static function generate_unique_block_slug( $block, $slugs, $prefix ) {
1232 $slug = is_string( $block['blockName'] ) ? $block['blockName'] : '';
1233
1234 if ( ! empty( $block['attrs']['label'] ) && is_string( $block['attrs']['label'] ) ) {
1235 $slug = sanitize_title( $block['attrs']['label'] );
1236
1237 // If the label contains non-Latin characters (e.g. Japanese, Chinese),
1238 // sanitize_title() produces a percent-encoded slug like "%e3%83%95%e3%83%aa".
1239 // These are unstable and break conditional logic field matching.
1240 // Fall back to the block name to ensure a stable ASCII slug.
1241 if ( false !== strpos( $slug, '%' ) ) {
1242 $block_name = is_string( $block['blockName'] ) ? $block['blockName'] : '';
1243 // Strip the 'srfm/' namespace to match JS-side cleanForSlug() output.
1244 $block_name = (string) preg_replace( '/^srfm\//', '', $block_name );
1245 $slug = sanitize_title( $block_name );
1246 }
1247 }
1248
1249 if ( ! empty( $prefix ) ) {
1250 $slug = $prefix . '-' . $slug;
1251 }
1252
1253 return self::generate_slug( $slug, $slugs );
1254 }
1255
1256 /**
1257 * This function ensures that the slug is unique.
1258 * If the slug is already taken, it appends a number to the slug to make it unique.
1259 *
1260 * @param string $slug test to be converted to slug.
1261 * @param array<string> $slugs An array of existing slugs.
1262 * @since 0.0.10
1263 * @return string The unique slug.
1264 */
1265 public static function generate_slug( $slug, $slugs ) {
1266 $slug = sanitize_title( $slug );
1267
1268 if ( ! in_array( $slug, $slugs, true ) ) {
1269 return $slug;
1270 }
1271
1272 $index = 1;
1273
1274 while ( in_array( $slug . '-' . $index, $slugs, true ) ) {
1275 $index++;
1276 }
1277
1278 return $slug . '-' . $index;
1279 }
1280
1281 /**
1282 * Encode data to JSON. This function will encode the data with JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE.
1283 *
1284 * @since 0.0.11
1285 * @param array<mixed> $data The data to encode.
1286 * @return string|false The JSON representation of the value on success or false on failure.
1287 */
1288 public static function encode_json( $data ) {
1289 return wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
1290 }
1291
1292 /**
1293 * Returns true if SureTriggers plugin is ready for the custom app.
1294 *
1295 * @since 1.0.3
1296 * @return bool Returns true if SureTriggers plugin is ready for the custom app.
1297 */
1298 public static function is_suretriggers_ready() {
1299 if ( ! defined( 'SURE_TRIGGERS_FILE' ) ) {
1300 // Probably plugin is de-activated or not installed at all.
1301 return false;
1302 }
1303
1304 $suretriggers_data = get_option( 'suretrigger_options', [] );
1305 if ( ! is_array( $suretriggers_data ) || empty( $suretriggers_data['secret_key'] ) || ! is_string( $suretriggers_data['secret_key'] ) ) {
1306 // SureTriggers is not authenticated yet.
1307 return false;
1308 }
1309
1310 return true;
1311 }
1312
1313 /**
1314 * Registers script translations for a specific handle.
1315 *
1316 * This function sets the script translations for a given script handle, allowing
1317 * localization of JavaScript strings using the specified text domain and path.
1318 *
1319 * @param string $handle The script handle to apply translations to.
1320 * @param string $domain Optional. The text domain for translations. Default is 'sureforms'.
1321 * @param string $path Optional. The path to the translation files. Default is the 'languages' folder in the SureForms directory.
1322 *
1323 * @since 1.0.5
1324 * @return void
1325 */
1326 public static function register_script_translations( $handle, $domain = 'sureforms', $path = SRFM_DIR . 'languages' ) {
1327 wp_set_script_translations( $handle, $domain, $path );
1328 }
1329
1330 /**
1331 * Validates whether the specified conditions or a single key-value pair exist in the request context.
1332 *
1333 * - If `$conditions` is provided as an array, it will validate all key-value pairs in `$conditions`
1334 * against the `$_REQUEST` superglobal.
1335 * - If `$conditions` is empty, it validates a single key-value pair from `$key` and `$value`.
1336 *
1337 * @param string $value The expected value to match in the request if `$conditions` is not used.
1338 * @param string $key The key to check for in the request if `$conditions` is not used.
1339 * @param array<string, string> $conditions An optional associative array of key-value pairs to validate.
1340 * @since 1.1.1
1341 * @return bool Returns true if all conditions are met or the single key-value pair is valid, otherwise false.
1342 */
1343 public static function validate_request_context( $value, $key = 'post_type', $conditions = [] ) {
1344 // If conditions are provided, validate all key-value pairs in the conditions array.
1345 if ( ! empty( $conditions ) ) {
1346 foreach ( $conditions as $condition_key => $condition_value ) {
1347 if ( ! isset( $_REQUEST[ $condition_key ] ) || $_REQUEST[ $condition_key ] !== $condition_value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a controlled comparison of request values.
1348 // Return false if any condition is not satisfied.
1349 return false;
1350 }
1351 }
1352 // Return true if all conditions are satisfied.
1353 return true;
1354 }
1355
1356 // Validate $value and $key when no conditions are provided.
1357 if ( empty( $key ) || empty( $value ) ) {
1358 return false;
1359 }
1360
1361 // Validate a single key-value pair when no conditions are provided.
1362 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.
1363 }
1364
1365 /**
1366 * Retrieve the list of excluded fields for form data processing.
1367 *
1368 * This method returns an array of field keys that should be excluded when
1369 * processing form data.
1370 *
1371 * @since 1.1.1
1372 * @return array<string> Returns the string array of excluded fields.
1373 */
1374 public static function get_excluded_fields() {
1375 $excluded_fields = [ 'srfm-honeypot-field', 'g-recaptcha-response', 'srfm-sender-email-field', 'form-id' ];
1376
1377 return apply_filters( 'srfm_excluded_fields', $excluded_fields );
1378 }
1379
1380 /**
1381 * Check whether the current page is a SureForms admin page.
1382 *
1383 * @since 1.2.2
1384 * @return bool Returns true if the current page is a SureForms admin page, otherwise false.
1385 */
1386 public static function is_sureforms_admin_page() {
1387 $current_screen = get_current_screen();
1388 $is_screen_sureforms_menu = self::validate_request_context( 'sureforms_menu', 'page' );
1389 $is_screen_add_new_form = self::validate_request_context( 'add-new-form', 'page' );
1390 $is_screen_sureforms_form_settings = self::validate_request_context( 'sureforms_form_settings', 'page' );
1391 $is_screen_sureforms_entries = self::validate_request_context( SRFM_ENTRIES, 'page' );
1392 $is_post_type_sureforms_form = $current_screen && SRFM_FORMS_POST_TYPE === $current_screen->post_type;
1393
1394 return $is_screen_sureforms_menu || $is_screen_add_new_form || $is_screen_sureforms_form_settings || $is_screen_sureforms_entries || $is_post_type_sureforms_form;
1395 }
1396
1397 /**
1398 * Filters and concatenates valid class names from an array.
1399 *
1400 * @param array<string> $class_names The array containing potential class names.
1401 * @since 1.4.0
1402 * @return string The concatenated string of valid class names separated by spaces.
1403 */
1404 public static function join_strings( $class_names ) {
1405 // Filter the array to include only valid class names.
1406 $valid_class_names = array_filter(
1407 $class_names,
1408 static function ( $value ) {
1409 return is_string( $value ) && '' !== $value && false !== $value;
1410 }
1411 );
1412
1413 // Concatenate the valid class names with spaces and return.
1414 return implode( ' ', $valid_class_names );
1415 }
1416 /**
1417 * Get SureForms Website URL.
1418 *
1419 * @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.
1420 * @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'].
1421 * @since 0.0.7
1422 * @return string
1423 */
1424 public static function get_sureforms_website_url( $trail, $utm_args = [] ) {
1425 $url = SRFM_WEBSITE;
1426 if ( ! empty( $trail ) && is_string( $trail ) ) {
1427 $url = SRFM_WEBSITE . $trail;
1428 }
1429
1430 if ( ! is_array( $utm_args ) ) {
1431 $utm_args = [];
1432 }
1433
1434 if ( class_exists( 'BSF_UTM_Analytics' ) ) {
1435 $url = \BSF_UTM_Analytics::get_utm_ready_link( $url, 'sureforms', $utm_args );
1436 }
1437
1438 return esc_url( $url );
1439 }
1440
1441 /**
1442 * Validates if the given string is a valid CSS class name.
1443 *
1444 * A valid CSS class name:
1445 * - Does not start with a digit, hyphen, or underscore.
1446 * - Can contain alphanumeric characters, underscores, hyphens, and Unicode letters.
1447 *
1448 * @param string $class_name The class name to validate.
1449 *
1450 * @since 1.3.1
1451 * @return bool True if the class name is valid, otherwise false.
1452 */
1453 public static function is_valid_css_class_name( $class_name ) {
1454 // Regular expression to validate a Unicode-aware CSS class name.
1455 $class_name_regex = '/^[^\d\-_][\w\p{L}\p{N}\-_]*$/u';
1456
1457 // Check if the className matches the pattern.
1458 return preg_match( $class_name_regex, $class_name ) === 1;
1459 }
1460
1461 /**
1462 * Get the gradient css for given gradient parameters.
1463 *
1464 * @param string $type The type of gradient. Default 'linear'.
1465 * @param string $color1 The first color of the gradient. Default '#FFC9B2'.
1466 * @param string $color2 The second color of the gradient. Default '#C7CBFF'.
1467 * @param int $loc1 The location of the first color. Default 0.
1468 * @param int $loc2 The location of the second color. Default 100.
1469 * @param int $angle The angle of the gradient. Default 90.
1470 *
1471 * @since 1.4.4
1472 * @return string The gradient css.
1473 */
1474 public static function get_gradient_css( $type = 'linear', $color1 = '#FFC9B2', $color2 = '#C7CBFF', $loc1 = 0, $loc2 = 100, $angle = 90 ) {
1475 if ( 'linear' === $type ) {
1476 return "linear-gradient({$angle}deg, {$color1} {$loc1}%, {$color2} {$loc2}%)";
1477 }
1478 return "radial-gradient({$color1} {$loc1}%, {$color2} {$loc2}%)";
1479 }
1480
1481 /**
1482 * Return the classes based on background and overlay type to add to the form container.
1483 *
1484 * @param string $background_type The background type.
1485 * @param string $overlay_type The overlay type.
1486 * @param string $bg_image The background image url.
1487 *
1488 * @since 1.4.4
1489 * @return string The classes to add to the form container.
1490 */
1491 public static function get_background_classes( $background_type, $overlay_type, $bg_image = '' ) {
1492 if ( empty( $background_type ) ) {
1493 $background_type = 'color';
1494 }
1495
1496 $background_type_class = '';
1497 $overlay_class = 'image' === $background_type && ! empty( $bg_image ) && $overlay_type ? "srfm-overlay-{$overlay_type}" : '';
1498
1499 // Set the class based on the background type.
1500 switch ( $background_type ) {
1501 case 'image':
1502 $background_type_class = 'srfm-bg-image';
1503 break;
1504 case 'gradient':
1505 $background_type_class = 'srfm-bg-gradient';
1506 break;
1507 default:
1508 $background_type_class = 'srfm-bg-color';
1509 break;
1510 }
1511
1512 return self::join_strings( [ $background_type_class, $overlay_class ] );
1513 }
1514
1515 /**
1516 * Custom escape function for the textarea with rich text support.
1517 *
1518 * @param string $content The content submitted by the user in the textarea block.
1519 * @since 1.7.1
1520 *
1521 * @return string Escaped content.
1522 */
1523 public static function esc_textarea( $content ) {
1524 $content = wpautop( self::sanitize_textarea( $content ) );
1525
1526 return trim( str_replace( [ "\r\n", "\r", "\n" ], '', $content ) );
1527 }
1528
1529 /**
1530 * Custom sanitization function for the textarea with rich text support.
1531 *
1532 * @param string $content The content submitted by the user in the textarea block.
1533 * @since 1.7.1
1534 *
1535 * @return string Sanitized content.
1536 */
1537 public static function sanitize_textarea( $content ) {
1538 $count = 1;
1539 $content = convert_invalid_entities( $content );
1540
1541 // Remove the 'script' and 'style' tags recursively from the content.
1542 while ( $count ) {
1543 $content = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', self::get_string_value( $content ), - 1, $count );
1544 }
1545
1546 // Disable the safe style attribute parsing for the textarea block.
1547 add_filter( 'safe_style_css', [ self::class, 'disable_style_attr_parsing' ], 10, 1 );
1548 $content = wp_kses_post( self::get_string_value( $content ) );
1549
1550 // Remove the filter after sanitization to avoid affecting other blocks.
1551 remove_filter( 'safe_style_css', [ self::class, 'disable_style_attr_parsing' ], 10 );
1552
1553 // Ensure all tags are balanced.
1554 return force_balance_tags( $content );
1555 }
1556
1557 /**
1558 * Disable parsing of style attributes for the textarea block.
1559 *
1560 * @param array<string> $allowed_styles The allowed styles.
1561 * @since 1.7.1
1562 *
1563 * @return array An empty array to disable style attribute parsing.
1564 */
1565 public static function disable_style_attr_parsing( $allowed_styles ) {
1566 unset( $allowed_styles );
1567 // Disable parsing of style attributes.
1568 return [];
1569 }
1570 /**
1571 * Strips JavaScript attributes from HTML content.
1572 *
1573 * @param string $html The HTML content to process.
1574 * @param bool $remove_link_target Optional. When true, removes target and strips noopener/noreferrer from rel on links. Default false.
1575 * @since 1.7.1
1576 * @since 2.5.2 Added $remove_link_target parameter.
1577 * @return string The cleaned HTML content without JavaScript attributes.
1578 */
1579 public static function strip_js_attributes( $html, $remove_link_target = false ) {
1580 $dom = new \DOMDocument();
1581
1582 // Suppress warnings due to malformed HTML.
1583 libxml_use_internal_errors( true );
1584 $loaded = $dom->loadHTML( '<?xml encoding="utf-8" ?>' . $html );
1585 libxml_clear_errors();
1586
1587 if ( ! $loaded ) {
1588 return $html; // Return original HTML if loading fails.
1589 }
1590
1591 $xpath = new \DOMXPath( $dom );
1592
1593 // 1. Remove all <script> tags.
1594 $script_nodes = $xpath->query( '//script' );
1595 if ( $script_nodes instanceof \DOMNodeList ) {
1596 foreach ( $script_nodes as $script ) {
1597 // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- This is a DOM element.
1598 $parent_node = $script->parentNode;
1599 if ( $parent_node instanceof \DOMNode ) {
1600 $parent_node->removeChild( $script );
1601 }
1602 }
1603 }
1604
1605 // 2. Remove all attributes that start with "on" (like onclick, onmouseover, etc.).
1606 $elements_with_on_attrs = $xpath->query( '//*[@*[starts-with(name(), "on")]]' );
1607 if ( $elements_with_on_attrs instanceof \DOMNodeList ) {
1608 foreach ( $elements_with_on_attrs as $element ) {
1609 if ( $element instanceof \DOMElement && $element->hasAttributes() ) {
1610 foreach ( iterator_to_array( $element->attributes ) as $attr ) {
1611 if ( $attr instanceof \DOMAttr && stripos( $attr->name, 'on' ) === 0 ) {
1612 $element->removeAttribute( $attr->name );
1613 }
1614 }
1615 }
1616 }
1617 }
1618
1619 // 3. Optionally remove target and target-related rel values (noopener, noreferrer) from links.
1620 if ( $remove_link_target ) {
1621 $links = $xpath->query( '//a[@target]' );
1622 if ( $links instanceof \DOMNodeList ) {
1623 foreach ( $links as $link ) {
1624 if ( $link instanceof \DOMElement ) {
1625 $link->removeAttribute( 'target' );
1626 $rel = $link->getAttribute( 'rel' );
1627 if ( $rel ) {
1628 $cleaned_rel = trim( (string) preg_replace( '/\s+/', ' ', (string) preg_replace( '/\b(noopener|noreferrer)\b/i', '', $rel ) ) );
1629 if ( $cleaned_rel ) {
1630 $link->setAttribute( 'rel', $cleaned_rel );
1631 } else {
1632 $link->removeAttribute( 'rel' );
1633 }
1634 }
1635 }
1636 }
1637 }
1638 }
1639
1640 // Return cleaned HTML.
1641 $body = $dom->getElementsByTagName( 'body' )->item( 0 );
1642 if ( $body instanceof \DOMNode ) {
1643 $cleaned_html = $dom->saveHTML( $body );
1644 return is_string( $cleaned_html ) ? $cleaned_html : '';
1645 }
1646 return '';
1647 }
1648
1649 /**
1650 * Encodes the given string with base64.
1651 * Moved from admin class to here.
1652 *
1653 * @param string $logo contains svg's.
1654 * @return string
1655 */
1656 public static function encode_svg( $logo ) {
1657 return 'data:image/svg+xml;base64,' . base64_encode( $logo ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1658 }
1659
1660 /**
1661 * Get plugin status
1662 *
1663 * @since 0.0.1
1664 * @since 1.7.0 moved to inc/helper.php from inc/admin-ajax.php
1665 *
1666 * @param string $plugin_init_file Plugin init file.
1667 * @return string
1668 */
1669 public static function get_plugin_status( $plugin_init_file ) {
1670
1671 $installed_plugins = get_plugins();
1672
1673 if ( ! isset( $installed_plugins[ $plugin_init_file ] ) ) {
1674 return 'Install';
1675 }
1676 if ( is_plugin_active( $plugin_init_file ) ) {
1677 return 'Activated';
1678 }
1679 return 'Installed';
1680 }
1681
1682 /**
1683 * Return the first installed plugin from a list, or a default if none exist.
1684 *
1685 * @since 2.0.0
1686 *
1687 * @param array<string> $plugins_to_check Plugin file paths to check, in priority order.
1688 * @param string $default Optional fallback plugin file path. Default empty string.
1689 *
1690 * @return string First installed plugin file path, or the default.
1691 */
1692 public static function get_plugin_if_installed( $plugins_to_check, $default = '' ) {
1693 if ( ! function_exists( 'get_plugins' ) ) {
1694 require_once ABSPATH . 'wp-admin/includes/plugin.php';
1695 }
1696
1697 $plugins = get_plugins();
1698
1699 foreach ( self::get_array_value( $plugins_to_check ) as $plugin_file ) {
1700 if ( isset( $plugins[ $plugin_file ] ) ) {
1701 return $plugin_file;
1702 }
1703 }
1704
1705 return $default;
1706 }
1707
1708 /**
1709 * Check which Starter Templates plugin is installed and return its main plugin file path.
1710 *
1711 * @since 1.7.3
1712 *
1713 * @return string The main plugin file path of the installed Starter Templates plugin.
1714 */
1715 public static function check_starter_template_plugin() {
1716 return self::get_plugin_if_installed(
1717 [ 'astra-pro-sites/astra-pro-sites.php' ],
1718 'astra-sites/astra-sites.php'
1719 );
1720 }
1721
1722 /**
1723 * Get sureforms recommended integrations.
1724 *
1725 * @since 0.0.1
1726 * @since 1.7.0 moved to inc/helper.php from inc/admin-ajax.php
1727 *
1728 * @return array<mixed>
1729 */
1730 public static function sureforms_get_integration() {
1731 $suretrigger_connected = apply_filters( 'suretriggers_is_user_connected', '' );
1732 $logo_sure_triggers = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suretriggers.svg' );
1733 $logo_full = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suretriggers_full.svg' );
1734 $logo_sure_mails = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suremails.svg' );
1735 $logo_uae = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/uae.svg' );
1736 $logo_starter_templates = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/starterTemplates.svg' );
1737 $logo_sure_rank = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/surerank.svg' );
1738 $logo_sure_contact = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/surecontact.svg' );
1739
1740 $integrations = [
1741 'sure_contact' => [
1742 'title' => __( 'SureContact', 'sureforms' ),
1743 'singleLineDescription' => __( 'Turn Emails Into Revenue with a CRM Built for Your Website!', 'sureforms' ),
1744 'subtitle' => __( 'Send newsletters, run campaigns, set up automations, manage contacts, and see exactly how much revenue your emails generate, all in one place.', 'sureforms' ),
1745 'status' => self::get_plugin_status( 'surecontact/surecontact.php' ),
1746 'slug' => 'surecontact',
1747 'path' => 'surecontact/surecontact.php',
1748 'logo' => self::encode_svg( is_string( $logo_sure_contact ) ? $logo_sure_contact : '' ),
1749 ],
1750 'sure_mails' => [
1751 'title' => __( 'SureMail', 'sureforms' ),
1752 'singleLineDescription' => __( 'Boost Your Email Deliverability Instantly!', 'sureforms' ),
1753 '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' ),
1754 'status' => self::get_plugin_status( 'suremails/suremails.php' ),
1755 'slug' => 'suremails',
1756 'path' => 'suremails/suremails.php',
1757 'logo' => self::encode_svg( is_string( $logo_sure_mails ) ? $logo_sure_mails : '' ),
1758 ],
1759 'sure_triggers' => [
1760 'title' => __( 'OttoKit', 'sureforms' ),
1761 'singleLineDescription' => __( 'Automate your WordPress workflows effortlessly.', 'sureforms' ),
1762 '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' ),
1763 'status' => self::get_plugin_status( 'suretriggers/suretriggers.php' ),
1764 'slug' => 'suretriggers',
1765 'path' => 'suretriggers/suretriggers.php',
1766 'logo' => self::encode_svg( is_string( $logo_sure_triggers ) ? $logo_sure_triggers : '' ),
1767 'logo_full' => self::encode_svg( is_string( $logo_full ) ? $logo_full : '' ),
1768 'connected' => $suretrigger_connected,
1769 'connection_url' => admin_url( 'admin.php?page=suretriggers' ),
1770 ],
1771 'starter_templates' => [
1772 'title' => __( 'Starter Templates', 'sureforms' ),
1773 'singleLineDescription' => __( 'Launch Beautiful Websites in Minutes!', 'sureforms' ),
1774 'subtitle' => __( 'Choose from professionally designed templates, import with one click, and customize effortlessly to match your brand.', 'sureforms' ),
1775 'status' => self::get_plugin_status( self::check_starter_template_plugin() ),
1776 'slug' => 'astra-sites',
1777 'path' => self::check_starter_template_plugin(),
1778 'logo' => self::encode_svg( is_string( $logo_starter_templates ) ? $logo_starter_templates : '' ),
1779 ],
1780 ];
1781
1782 $elementor_installed = self::get_plugin_if_installed( [ 'elementor/elementor.php' ] );
1783
1784 if ( $elementor_installed ) {
1785 $integrations['uae'] = [
1786 'title' => __( 'Ultimate Addons for Elementor', 'sureforms' ),
1787 'singleLineDescription' => __( 'Power Up Elementor to Build Stunning Websites Faster!', 'sureforms' ),
1788 'subtitle' => __( 'Enhance Elementor with powerful widgets and templates. Build stunning, high-performing websites faster with creative design elements and seamless customization.', 'sureforms' ),
1789 'status' => self::get_plugin_status( 'header-footer-elementor/header-footer-elementor.php' ),
1790 'slug' => 'header-footer-elementor',
1791 'path' => 'header-footer-elementor/header-footer-elementor.php',
1792 'logo' => self::encode_svg( is_string( $logo_uae ) ? $logo_uae : '' ),
1793 ];
1794 } else {
1795 $integrations['sure_rank'] = [
1796 'title' => __( 'SureRank', 'sureforms' ),
1797 'singleLineDescription' => __( 'Elevate Your SEO and Climb Search Rankings Effortlessly!', 'sureforms' ),
1798 'subtitle' => __( 'Boost your website\'s visibility with smart SEO automation. Optimize content, track keyword performance, and get actionable insights, all inside WordPress.', 'sureforms' ),
1799 'status' => self::get_plugin_status( 'surerank/surerank.php' ),
1800 'slug' => 'surerank',
1801 'path' => 'surerank/surerank.php',
1802 'logo' => self::encode_svg( is_string( $logo_sure_rank ) ? $logo_sure_rank : '' ),
1803 ];
1804 }
1805
1806 return apply_filters( 'srfm_integrated_plugins', $integrations );
1807 }
1808
1809 /**
1810 * Get the current rotating plugin for the banner.
1811 *
1812 * Plugins rotate every 2 days. Only non-activated plugins are shown.
1813 * Returns false if all plugins are activated.
1814 *
1815 * @since 2.0.0
1816 * @return array<string, mixed>|false The current plugin data or false if all plugins are activated.
1817 */
1818 public static function get_rotating_plugin_banner() {
1819 $all_plugins = self::sureforms_get_integration();
1820
1821 if ( ! is_array( $all_plugins ) ) {
1822 return false;
1823 }
1824
1825 $available_plugins = [];
1826
1827 // Only include non-activated plugins.
1828 foreach ( $all_plugins as $plugin ) {
1829 if ( ! is_array( $plugin ) ) {
1830 continue;
1831 }
1832 if ( isset( $plugin['status'] ) && is_string( $plugin['status'] ) && 'Activated' !== $plugin['status'] ) {
1833 $available_plugins[] = $plugin;
1834 }
1835 }
1836
1837 // Re-index the array to have sequential numeric keys.
1838 $available_plugins = array_values( $available_plugins );
1839 $total_plugins = count( $available_plugins );
1840
1841 // Hide section if all plugins are active.
1842 if ( 0 === $total_plugins ) {
1843 return false;
1844 }
1845
1846 // Get stored rotation data.
1847 $rotation_data = self::get_srfm_option( 'plugin_banner_rotation', [] );
1848
1849 if ( ! is_array( $rotation_data ) ) {
1850 $rotation_data = [];
1851 }
1852
1853 // Initialize rotation data if empty.
1854 if ( empty( $rotation_data ) ) {
1855 $current_time = time();
1856 self::update_srfm_option(
1857 'plugin_banner_rotation',
1858 [
1859 'last_rotation_date' => $current_time,
1860 'plugin_index' => 0,
1861 ]
1862 );
1863 return isset( $available_plugins[0] ) && is_array( $available_plugins[0] ) ? $available_plugins[0] : false;
1864 }
1865
1866 $last_rotation_date = isset( $rotation_data['last_rotation_date'] ) && is_int( $rotation_data['last_rotation_date'] ) ? $rotation_data['last_rotation_date'] : 0;
1867 $plugin_index = isset( $rotation_data['plugin_index'] ) && is_numeric( $rotation_data['plugin_index'] ) ? intval( $rotation_data['plugin_index'] ) : 0;
1868
1869 $current_time = time();
1870 $days_since_rotation = ( $current_time - $last_rotation_date ) / DAY_IN_SECONDS;
1871
1872 // Rotate every 2 days.
1873 if ( $days_since_rotation >= 2 ) {
1874 // Rotate to next plugin.
1875 ++$plugin_index;
1876 $plugin_index %= $total_plugins;
1877
1878 // Update the rotation data.
1879 self::update_srfm_option(
1880 'plugin_banner_rotation',
1881 [
1882 'last_rotation_date' => $current_time,
1883 'plugin_index' => $plugin_index,
1884 ]
1885 );
1886 }
1887
1888 // Ensure the index is within bounds.
1889 if ( $plugin_index >= $total_plugins ) {
1890 $plugin_index = 0;
1891 }
1892
1893 return isset( $available_plugins[ $plugin_index ] ) && is_array( $available_plugins[ $plugin_index ] ) ? $available_plugins[ $plugin_index ] : false;
1894 }
1895
1896 /**
1897 * Get a value from the srfm_options array.
1898 *
1899 * @param string $key The key to retrieve.
1900 * @param mixed $default The default value to return if the key does not exist.
1901 * @since 1.8.0
1902 * @return mixed
1903 */
1904 public static function get_srfm_option( $key, $default = null ) {
1905 $options = get_option( 'srfm_options', [] );
1906 if ( ! is_array( $options ) ) {
1907 $options = [];
1908 }
1909 return array_key_exists( $key, $options ) ? $options[ $key ] : $default;
1910 }
1911
1912 /**
1913 * Update a value in the srfm_options array.
1914 *
1915 * @param string $key The key to update.
1916 * @param mixed $value The value to set.
1917 * @since 1.8.0
1918 * @return void
1919 */
1920 public static function update_srfm_option( $key, $value ) {
1921 $options = get_option( 'srfm_options', [] );
1922 if ( ! is_array( $options ) ) {
1923 $options = [];
1924 }
1925 $options[ $key ] = $value;
1926 update_option( 'srfm_options', $options );
1927 }
1928
1929 /**
1930 * Get the WordPress file types.
1931 *
1932 * @since 1.7.4
1933 * @return array<string,mixed> An associative array representing the file types.
1934 */
1935 public static function get_wp_file_types() {
1936 $formats = [];
1937 $mimes = get_allowed_mime_types();
1938 $maxsize = wp_max_upload_size() / 1048576;
1939 if ( ! empty( $mimes ) ) {
1940 foreach ( $mimes as $type => $mime ) {
1941 $multiple = explode( '|', $type );
1942 foreach ( $multiple as $single ) {
1943 $formats[] = $single;
1944 }
1945 }
1946 }
1947
1948 return [
1949 'formats' => $formats,
1950 'maxsize' => $maxsize,
1951 ];
1952 }
1953
1954 /**
1955 * Determines if the SureForms Pro plugin is installed and active.
1956 *
1957 * Checks for the presence of the SRFM_PRO_VER constant.
1958 *
1959 * @since 1.8.0
1960 *
1961 * @return bool True if the Pro plugin is active; false otherwise.
1962 */
1963 public static function has_pro() {
1964 return defined( 'SRFM_PRO_VER' );
1965 }
1966
1967 /**
1968 * Verifies the request by checking the nonce and user capabilities.
1969 *
1970 * @param string $request_type The type of request, either 'rest' or 'ajax'.
1971 * @param string $nonce_action The action name for the nonce.
1972 * @param string $nonce_name The name of the nonce field.
1973 * @param string $capability The capability required to perform the action. Default is 'manage_options'.
1974 *
1975 * @since 1.10.0
1976 * @return void
1977 */
1978 public static function verify_nonce_and_capabilities( $request_type, $nonce_action, $nonce_name, $capability = 'manage_options' ) {
1979
1980 if ( ! is_string( $nonce_action ) || ! is_string( $nonce_name ) || empty( $nonce_action ) || empty( $nonce_name ) ) {
1981 wp_send_json_error(
1982 [ 'message' => __( 'Invalid nonce action or name.', 'sureforms' ) ],
1983 400
1984 );
1985 }
1986
1987 // Verify nonce for security.
1988 if ( 'rest' === $request_type ) {
1989 // For REST API requests, use the WP_REST_Request object to verify the nonce.
1990 if ( ! wp_verify_nonce( $nonce_action, $nonce_name ) ) {
1991 wp_send_json_error(
1992 [ 'message' => __( 'Invalid security token.', 'sureforms' ) ],
1993 403
1994 );
1995 }
1996 } elseif ( 'ajax' === $request_type ) {
1997 // For non-REST requests, use the standard nonce verification.
1998 if ( ! check_ajax_referer( $nonce_action, $nonce_name, false ) ) {
1999 wp_send_json_error(
2000 [ 'message' => __( 'Invalid security token.', 'sureforms' ) ],
2001 403
2002 );
2003 }
2004 } else {
2005 // If the request type is not recognized, return an error.
2006 wp_send_json_error(
2007 [ 'message' => __( 'Invalid request type.', 'sureforms' ) ],
2008 400
2009 );
2010 }
2011
2012 // Check user capabilities.
2013 if ( ! current_user_can( $capability ) ) {
2014 wp_send_json_error(
2015 [ 'message' => esc_html__( 'You do not have permission to perform this action.', 'sureforms' ) ],
2016 403
2017 );
2018 }
2019 }
2020
2021 /**
2022 * Get the block name from a field name by extracting the first two parts.
2023 *
2024 * @param string $field_name The full field name (e.g., 'srfm-text-lbl-123').
2025 *
2026 * @since 1.11.0
2027 * @return string The block name (e.g., 'srfm-text').
2028 */
2029 public static function get_block_name_from_field( $field_name ) {
2030 return implode( '-', array_slice( explode( '-', explode( '-lbl-', $field_name )[0] ), 0, 2 ) );
2031 }
2032
2033 /**
2034 * Check if any of the top 10 popular WordPress SMTP plugins is active using array_intersect.
2035 *
2036 * @since 1.9.1
2037 * @return bool True if any SMTP plugin is active, false otherwise.
2038 */
2039 public static function is_any_smtp_plugin_active() {
2040 $smtp_plugins = [
2041 'wp-mail-smtp/wp_mail_smtp.php',
2042 'post-smtp/postman-smtp.php',
2043 'easy-wp-smtp/easy-wp-smtp.php',
2044 'wp-smtp/wp-smtp.php',
2045 'newsletter/plugin.php',
2046 'fluent-smtp/fluent-smtp.php',
2047 'pepipost-smtp/pepipost-smtp.php',
2048 'mail-bank/wp-mail-bank.php',
2049 'smtp-mailer/smtp-mailer.php',
2050 'suremails/suremails.php',
2051 'site-mailer/site-mailer.php',
2052 ];
2053
2054 $active_plugins = (array) get_option( 'active_plugins', [] );
2055 // For multisite, merge sitewide active plugins.
2056 if ( is_multisite() ) {
2057 $network_plugins = (array) get_site_option( 'active_sitewide_plugins', [] );
2058 $active_plugins = array_merge( $active_plugins, array_keys( $network_plugins ) );
2059 }
2060
2061 return (bool) array_intersect( $smtp_plugins, $active_plugins );
2062 }
2063
2064 /**
2065 * Apply a filter and return the filtered value only if it's a non-empty array.
2066 * Otherwise, return the default array.
2067 *
2068 * @param string $filter_name The name of the filter to apply.
2069 * @param mixed $default The default array to return if the filtered result is invalid.
2070 * @param mixed ...$args Additional arguments to pass to the filter.
2071 *
2072 * @return array The filtered array if valid, otherwise the default.
2073 */
2074 public static function apply_filters_as_array( $filter_name, $default, ...$args ) {
2075 // Ensure $default is an array.
2076 if ( ! is_array( $default ) ) {
2077 $default = [];
2078 }
2079
2080 // Validate the filter name.
2081 if ( ! is_string( $filter_name ) || empty( $filter_name ) ) {
2082 return $default;
2083 }
2084
2085 // Apply the filter with additional arguments.
2086 $filtered = apply_filters( $filter_name, $default, ...$args );
2087
2088 // Return filtered result if it's a non-empty array.
2089 return is_array( $filtered ) && ! empty( $filtered ) ? $filtered : $default;
2090 }
2091
2092 /**
2093 * Get forms with entry counts for a specific time period.
2094 *
2095 * @param int $timestamp The timestamp to get entries after.
2096 * @param int $limit Maximum number of forms to return (0 for all).
2097 * @param bool $sort Whether to sort by entry count descending.
2098 * @return array Array of form data with entry counts.
2099 * @since 1.9.1
2100 */
2101 public static function get_forms_with_entry_counts( $timestamp, $limit = 0, $sort = true ) {
2102 // Get all published forms with post objects for bulk title access.
2103 $args = [
2104 'post_type' => SRFM_FORMS_POST_TYPE,
2105 'posts_per_page' => -1,
2106 'post_status' => 'publish',
2107 'orderby' => 'ID',
2108 'order' => 'DESC',
2109 'no_found_rows' => true,
2110 'update_post_term_cache' => false,
2111 'update_post_meta_cache' => false,
2112 ];
2113
2114 $query = new \WP_Query( $args );
2115
2116 if ( ! $query->have_posts() ) {
2117 return [];
2118 }
2119
2120 $all_forms = [];
2121
2122 // Process posts directly from the query results without touching global $post.
2123 foreach ( $query->posts as $form ) {
2124 // Ensure we have a valid post object.
2125 if ( ! $form instanceof \WP_Post ) {
2126 continue;
2127 }
2128
2129 $form_id = (int) $form->ID;
2130 if ( $form_id <= 0 ) {
2131 continue;
2132 }
2133
2134 // Get entries count after the timestamp for this specific form.
2135 $entry_count = Entries::get_entries_count_after( $timestamp, $form_id );
2136
2137 // Get form title directly from post object, use "Blank Form" if empty.
2138 $form_title = $form->post_title;
2139 if ( empty( trim( self::get_string_value( $form_title ) ) ) ) {
2140 $form_title = __( 'Blank Form', 'sureforms' );
2141 }
2142
2143 $all_forms[] = [
2144 'form_id' => $form_id,
2145 'title' => $form_title,
2146 'count' => $entry_count,
2147 ];
2148 }
2149
2150 // Sort by count descending, then by form_id descending for consistency.
2151 if ( $sort ) {
2152 usort(
2153 $all_forms,
2154 static function( $a, $b ) {
2155 if ( $a['count'] === $b['count'] ) {
2156 return $b['form_id'] - $a['form_id'];
2157 }
2158 return $b['count'] - $a['count'];
2159 }
2160 );
2161 }
2162
2163 // Return limited results if specified.
2164 if ( $limit > 0 ) {
2165 return array_slice( $all_forms, 0, $limit );
2166 }
2167
2168 return $all_forms;
2169 }
2170
2171 /**
2172 * Check if the given form ID is valid SureForms form ID.
2173 * A valid form ID is a numeric value that corresponds to an existing SureForms form in the database.
2174 *
2175 * @since 1.9.1
2176 *
2177 * @param int|string|mixed $form_id The form ID to validate.
2178 * @return bool True if the form ID is valid, false otherwise.
2179 */
2180 public static function is_valid_form( $form_id ) {
2181
2182 // Check for a valid form ID.
2183 if ( empty( $form_id ) || ! is_numeric( $form_id ) ) {
2184 return false;
2185 }
2186
2187 // Check if the form ID exists in the database.
2188 $form = get_post( self::get_integer_value( $form_id ) );
2189
2190 // If the form does not exist or is not of the correct post type, return false.
2191 if ( ! $form || ! is_a( $form, 'WP_Post' ) || SRFM_FORMS_POST_TYPE !== $form->post_type ) {
2192 return false;
2193 }
2194
2195 return true;
2196 }
2197
2198 /**
2199 * Get the timestamp from a string.
2200 *
2201 * This function uses WordPress's configured timezone (from Settings → General → Timezone)
2202 * to ensure consistent behavior regardless of the server's timezone settings.
2203 *
2204 * @param string $date The date in YYYY-MM-DD format (e.g., '2026-01-10').
2205 * @param string $hours The hours in 12-hour format (e.g., '12', '01'-'12').
2206 * @param string $minutes The minutes (e.g., '00', '00'-'59').
2207 * @param string $meridiem The meridiem (e.g., 'AM' or 'PM').
2208 *
2209 * @since 1.10.1
2210 * @return int|false The timestamp if successful, false otherwise.
2211 */
2212 public static function get_timestamp_from_string( $date, $hours = '12', $minutes = '00', $meridiem = 'AM' ) {
2213
2214 if ( empty( $date ) || ! is_string( $date ) ) {
2215 return false; // Invalid input.
2216 }
2217
2218 // Ensure the date is in a valid format of YYYY-MM-DD.
2219 if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $date ) ) {
2220 return false; // Invalid date format.
2221 }
2222
2223 $time_string = $date . ' ' . $hours . ':' . $minutes . ' ' . $meridiem;
2224
2225 // Convert to timestamp using WordPress timezone.
2226 // This ensures the date/time is interpreted in the site's configured timezone,
2227 // not the server's timezone or PHP's default timezone.
2228 try {
2229 $datetime = date_create( $time_string, wp_timezone() );
2230
2231 if ( false === $datetime ) {
2232 return false;
2233 }
2234
2235 $timestamp = $datetime->getTimestamp();
2236
2237 if ( is_int( $timestamp ) && $timestamp > 0 ) {
2238 return $timestamp;
2239 }
2240 } catch ( \Exception $e ) {
2241 // If timezone conversion fails, return false.
2242 return false;
2243 }
2244
2245 // If conversion fails, return false.
2246 return false;
2247 }
2248
2249 /**
2250 * Generate a unique ID for the saved form.
2251 * Also ensures that the generated ID does not already exist in the database table.
2252 *
2253 * @param class-string $class The class name where the get method is defined to check for existing IDs.
2254 * @param int<1, max> $length The length of the random bytes to generate. Default is 8.
2255 * @return string
2256 * @since 2.2.0
2257 */
2258 public static function generate_unique_id( $class, $length = 8 ) {
2259 // Ensure length is at least 1.
2260 $length = max( 1, $length );
2261
2262 do {
2263 $id = bin2hex( random_bytes( $length ) );
2264 } while ( is_callable( [ $class, 'get' ] ) && call_user_func( [ $class, 'get' ], $id ) );
2265 return $id;
2266 }
2267
2268 /**
2269 * Log error messages to the error log.
2270 *
2271 * This function checks if error_log function exists, validates the message,
2272 * and logs it with the print_r second argument set to true.
2273 *
2274 * Logging is disabled by default. To enable logging, add this to wp-config.php:
2275 * define( 'SRFM_LOG', true );
2276 *
2277 * @param mixed $message The error message to log. Can be string or any type.
2278 * @param string $prefix Optional prefix to add before the message. Default: 'Log :'.
2279 *
2280 * @since 2.0.0
2281 * @return void
2282 */
2283 public static function srfm_log( $message, $prefix = 'Log :' ) {
2284 // Check if logging is enabled via SRFM_LOG constant.
2285 if ( ! defined( 'SRFM_LOG' ) ) {
2286 return;
2287 }
2288 unset( $message, $prefix );
2289 }
2290
2291 /**
2292 * Encodes data to base64 after JSON encoding with validation.
2293 *
2294 * This function checks if the data is non-empty and valid for JSON encoding.
2295 * If data is not valid, returns an empty string.
2296 * Otherwise, it attempts to JSON encode and then base64 encode the result.
2297 *
2298 * @param mixed $data The data to JSON encode and then base64 encode.
2299 * @return string The base64-encoded JSON string, or empty string on failure.
2300 */
2301 public static function srfm_base64_json_encode( $data ) {
2302 if ( empty( $data ) || ! is_array( $data ) ) {
2303 return '';
2304 }
2305
2306 $json = wp_json_encode( $data );
2307 if ( false === $json || '' === $json ) {
2308 return '';
2309 }
2310
2311 // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2312 return base64_encode( $json );
2313 }
2314
2315 }
2316