PluginProbe ʕ •ᴥ•ʔ
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz / 2.12.4
SureForms – Contact Form Builder, AI Forms, Payment Form, Survey & Quiz v2.12.4
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 0.0.4 0.0.5 0.0.6 0.0.7 0.0.8 0.0.9 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.1.0 1.1.1 1.1.2 1.10.0 1.10.1 1.11.0 1.12.0 1.12.1 1.12.2 1.12.3 1.13.0 1.13.1 1.13.2 1.2.0 1.2.1 1.2.2 1.2.3 1.2.4 1.2.5 1.3.0 1.3.1 1.3.2 1.4.0 1.4.1 1.4.2 1.4.3 1.4.4 1.4.5 1.5.0 1.5.1 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 1.6.5 1.7.0 1.7.1 1.7.2 1.7.3 1.7.4 1.8.0 1.9.0 1.9.1 2.0.0 2.0.1 2.0.2 2.1.0 2.1.1 2.2.0 2.2.1 2.2.2 2.3.0 2.4.0 2.5.0 2.5.2 2.6.0
sureforms / inc / helper.php
sureforms / inc Last commit date
abilities 3 weeks ago admin 3 months ago ai-form-builder 1 month ago blocks 2 months ago compatibility 3 weeks ago database 3 weeks ago email 3 weeks ago fields 3 weeks ago global-settings 1 month ago lib 1 month ago migrator 2 months ago page-builders 3 weeks ago payments 3 weeks ago single-form-settings 2 months ago traits 2 months ago activator.php 1 year ago admin-ajax.php 2 months ago background-process.php 9 months ago create-new-form.php 3 months ago duplicate-form.php 3 months ago entries.php 3 weeks ago events-scheduler.php 2 years ago export.php 3 months ago field-validation.php 3 weeks ago form-restriction.php 2 months ago form-styling.php 1 month ago form-submit.php 3 weeks ago forms-data.php 5 months ago frontend-assets.php 1 month ago generate-form-markup.php 1 week ago gutenberg-hooks.php 1 week ago helper.php 3 weeks ago learn.php 4 months ago onboarding.php 2 months ago post-types.php 1 week ago rest-api.php 1 week ago smart-tags.php 4 months ago submit-token.php 5 months ago translatable.php 1 month ago updater-callbacks.php 3 weeks ago updater.php 3 weeks ago
helper.php
2709 lines
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\Compatibility\Multilingual\String_Translator;
12 use SRFM\Inc\Database\Tables\Entries;
13 use SRFM\Inc\Traits\Get_Instance;
14 use WP_Error;
15 use WP_Post;
16
17 if ( ! defined( 'ABSPATH' ) ) {
18 exit; // Exit if accessed directly.
19 }
20
21 /**
22 * Sureforms Helper Class.
23 *
24 * @since 0.0.1
25 */
26 class Helper {
27 use Get_Instance;
28
29 /**
30 * Allowed HTML tags for SVG.
31 *
32 * @var array<string, array<string, bool>>
33 */
34 public static $allowed_tags_svg = [
35 'span' => [
36 'class' => true,
37 'aria-hidden' => true,
38 ],
39 'svg' => [
40 'xmlns' => true,
41 'width' => true,
42 'height' => true,
43 'viewBox' => true,
44 'fill' => true,
45 ],
46 'path' => [
47 'd' => true,
48 'stroke' => true,
49 'stroke-opacity' => true,
50 'stroke-width' => true,
51 'stroke-linecap' => true,
52 'stroke-linejoin' => true,
53 ],
54 ];
55
56 /**
57 * Sureforms SVGs.
58 *
59 * @var mixed srfm_svgs
60 */
61 private static $srfm_svgs = null;
62
63 /**
64 * Get common error message.
65 *
66 * @since 0.0.2
67 * @return array<string>
68 */
69 public static function get_common_err_msg() {
70 $translator = String_Translator::get_instance();
71 return [
72 'required' => $translator->translate_validation_message( 'srfm_required_field', __( 'This field is required.', 'sureforms' ) ),
73 'unique' => $translator->translate_validation_message( 'srfm_unique_field', __( 'Value needs to be unique.', 'sureforms' ) ),
74 ];
75 }
76
77 /**
78 * Convert a file URL to a file path.
79 *
80 * @param string $file_url The URL of the file.
81 *
82 * @since 1.3.0
83 * @return string The file path.
84 */
85 public static function convert_fileurl_to_filepath( $file_url ) {
86 static $upload_dir = null;
87 if ( ! $upload_dir ) {
88 // Internally cache the upload directory.
89 $upload_dir = wp_get_upload_dir();
90 }
91 return wp_normalize_path( str_replace( $upload_dir['baseurl'], $upload_dir['basedir'], $file_url ) );
92 }
93
94 /**
95 * Checks if current value is string or else returns default value
96 *
97 * @param mixed $data data which need to be checked if is string.
98 *
99 * @since 0.0.1
100 * @return string
101 */
102 public static function get_string_value( $data ) {
103 if ( is_scalar( $data ) ) {
104 return (string) $data;
105 }
106 if ( is_object( $data ) && method_exists( $data, '__toString' ) ) {
107 return $data->__toString();
108 }
109 if ( is_null( $data ) ) {
110 return '';
111 }
112 return '';
113 }
114 /**
115 * Checks if current value is number or else returns default value
116 *
117 * @param mixed $value data which need to be checked if is string.
118 * @param int $base value can be set is $data is not a string, defaults to empty string.
119 *
120 * @since 0.0.1
121 * @return int
122 */
123 public static function get_integer_value( $value, $base = 10 ) {
124 if ( is_numeric( $value ) ) {
125 return (int) $value;
126 }
127 if ( is_string( $value ) ) {
128 $trimmed_value = trim( $value );
129 return intval( $trimmed_value, $base );
130 }
131 return 0;
132 }
133
134 /**
135 * Validate a date string in Y-m-d format.
136 *
137 * @param string $date The date string to validate.
138 * @since 2.6.0
139 * @return bool
140 */
141 public static function validate_date( string $date ): bool {
142 $d = \DateTime::createFromFormat( 'Y-m-d', $date );
143 return $d && $d->format( 'Y-m-d' ) === $date;
144 }
145
146 /**
147 * Returns a boolean representation of the given value.
148 *
149 * @param mixed $data Data which needs to be converted to boolean.
150 *
151 * @since 2.5.2
152 * @return bool
153 */
154 public static function get_boolean_value( $data ) {
155 return (bool) $data;
156 }
157
158 /**
159 * Checks if current value is an array or else returns default value
160 *
161 * @param mixed $data Data which needs to be checked if it is an array.
162 *
163 * @since 0.0.3
164 * @return array
165 */
166 public static function get_array_value( $data ) {
167 if ( is_array( $data ) ) {
168 return $data;
169 }
170 if ( is_null( $data ) ) {
171 return [];
172 }
173 return (array) $data;
174 }
175
176 /**
177 * Extracts the field type from the dynamic field key ( or field slug ).
178 *
179 * @param string $field_key Dynamic field key.
180 * @since 0.0.6
181 * @return string Extracted field type.
182 */
183 public static function get_field_type_from_key( $field_key ) {
184
185 if ( false === strpos( $field_key, '-lbl-' ) ) {
186 return '';
187 }
188
189 return trim( explode( '-', $field_key )[1] );
190 }
191
192 /**
193 * Extracts the field label from the dynamic field key ( or field slug ).
194 *
195 * ALWAYS escape the return value at the sink. The label is decoded from the
196 * submitted key via {@see self::decode()}, so it is submitter-controlled and
197 * unauthenticated — and this method is strictly more dangerous than decode()
198 * alone, because it additionally runs html_entity_decode(), which expands
199 * entities and therefore undoes any htmlspecialchars()-on-store defence.
200 * When a label's integrity matters, read it from the form's stored block
201 * definitions by block id instead of from the submitted key.
202 *
203 * @param string $field_key Dynamic field key.
204 * @since 1.1.1
205 * @return string Extracted field label.
206 */
207 public static function get_field_label_from_key( $field_key ) {
208 if ( false === strpos( $field_key, '-lbl-' ) ) {
209 return '';
210 }
211
212 $label = explode( '-lbl-', $field_key )[1];
213 // Getting the encoded label. we are removing the block slug here.
214 $label = explode( '-', $label )[0];
215
216 // The result is submitter-controlled and unauthenticated — escape it for its
217 // context at the sink (esc_html, escape_csv_formula, ...), never trust it.
218 return $label ? html_entity_decode( self::decode( $label ) ) : '';
219 }
220
221 /**
222 * Extracts the block ID from the dynamic field key ( or field slug ).
223 *
224 * @param string $field_key Dynamic field key.
225 * @since 1.6.1
226 * @return string Extracted block ID.
227 */
228 public static function get_block_id_from_key( $field_key ) {
229 // Check if the key contains the block ID identifier.
230 if ( strpos( $field_key, 'srfm-' ) === 0 && strpos( $field_key, '-lbl-' ) === false ) {
231 return ''; // Return empty if the key format is invalid.
232 }
233
234 $parts = explode( '-lbl-', $field_key );
235 if ( isset( $parts[0] ) ) {
236 $block_id = explode( '-', $parts[0] );
237 if ( is_array( $block_id ) && ! empty( $block_id ) ) {
238 return end( $block_id );
239 }
240 }
241 return '';
242 }
243
244 /**
245 * Returns the proper sanitize callback functions according to the field type.
246 *
247 * @param string $field_type HTML field type.
248 * @since 0.0.6
249 * @return callable Returns sanitize callbacks according to the provided field type.
250 */
251 public static function get_field_type_sanitize_function( $field_type ) {
252 $callbacks = apply_filters(
253 'srfm_field_type_sanitize_functions',
254 [
255 'url' => 'esc_url_raw',
256 'input' => 'sanitize_text_field',
257 'number' => [ self::class, 'sanitize_number' ],
258 'email' => 'sanitize_email',
259 'textarea' => [ self::class, 'sanitize_textarea' ],
260 ]
261 );
262
263 return $callbacks[ $field_type ] ?? 'sanitize_text_field';
264 }
265
266 /**
267 * Sanitizes a numeric value.
268 *
269 * This function checks if the input value is numeric. If it is numeric, it sanitizes
270 * the value to ensure it's a float or integer, allowing for fractions and thousand separators.
271 * If the value is not numeric, it sanitizes it as a text field.
272 *
273 * @param mixed $value The value to be sanitized.
274 * @since 0.0.6
275 * @return int|float|string The sanitized value.
276 */
277 public static function sanitize_number( $value ) {
278 if ( ! is_numeric( $value ) ) {
279 // phpcs:ignore /** @phpstan-ignore-next-line */
280 return sanitize_text_field( $value ); // If it is not numeric, then let user get some sanitized data to view.
281 }
282
283 // phpcs:ignore /** @phpstan-ignore-next-line */
284 return sanitize_text_field( filter_var( $value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION | FILTER_FLAG_ALLOW_THOUSAND ) );
285 }
286
287 /**
288 * Sanitize a CSS value to prevent injection.
289 *
290 * Strips characters that can break out of a CSS property value context
291 * and removes dangerous CSS functions while preserving safe ones
292 * (rgb, hsl, linear-gradient, etc.).
293 *
294 * @param mixed $value Raw CSS value.
295 * @return string Sanitized CSS value.
296 * @since 2.7.0
297 */
298 public static function sanitize_css_value( $value ) {
299 $value = self::get_string_value( $value );
300 // Strip characters that can break out of a CSS property value context.
301 $value = preg_replace( '/[{}<>;\\\\"\'`]/', '', $value ) ?? '';
302 // Remove dangerous CSS functions (url, expression, import, etc.) while preserving safe ones (rgb, hsl, linear-gradient, etc.).
303 return preg_replace( '/\b(url|expression|import|javascript)\s*\(/i', '(', $value ) ?? '';
304 }
305
306 /**
307 * This function sanitizes the submitted form data according to the field type.
308 *
309 * @param array<mixed> $form_data $form_data User submitted form data.
310 * @since 0.0.6
311 * @return array<mixed> $result Sanitized form data.
312 */
313 public static function sanitize_by_field_type( $form_data ) {
314 $result = [];
315
316 if ( empty( $form_data ) || ! is_array( $form_data ) ) {
317 return $result;
318 }
319
320 foreach ( $form_data as $field_key => &$value ) {
321 $field_type = self::get_field_type_from_key( $field_key );
322 $sanitize_function = self::get_field_type_sanitize_function( $field_type );
323 $sanitized_data = is_array( $value ) ? self::sanitize_by_field_type( $value ) : call_user_func( $sanitize_function, $value );
324
325 $result[ $field_key ] = $sanitized_data;
326 }
327
328 return $result;
329 }
330
331 /**
332 * Sanitize a value based on its PHP type.
333 *
334 * Recursively sanitizes arrays while preserving native PHP types (bool, int, float).
335 * Use this for complex object metas with many properties where per-field callbacks are impractical.
336 *
337 * @param mixed $value The value to sanitize.
338 * @param int $depth Current recursion depth. Values nested beyond 10 levels are discarded.
339 * @since 2.8.0
340 * @return mixed The sanitized value.
341 */
342 public static function sanitize_by_type( $value, int $depth = 0 ) {
343 if ( $depth > 10 ) {
344 return '';
345 }
346 if ( is_array( $value ) ) {
347 $sanitized = [];
348 foreach ( $value as $key => $val ) {
349 $sanitized[ sanitize_text_field( (string) $key ) ] = self::sanitize_by_type( $val, $depth + 1 );
350 }
351 return $sanitized;
352 }
353 if ( is_bool( $value ) ) {
354 return $value;
355 }
356 if ( is_int( $value ) ) {
357 return intval( $value );
358 }
359 if ( is_float( $value ) ) {
360 return floatval( $value );
361 }
362 if ( is_string( $value ) ) {
363 return sanitize_text_field( $value );
364 }
365 return '';
366 }
367
368 /**
369 * This function performs array_map for multi dimensional array
370 *
371 * @param string $function function name to be applied on each element on array.
372 * @param array<mixed> $data_array array on which function needs to be performed.
373 * @return array<mixed>
374 * @since 0.0.1
375 */
376 public static function sanitize_recursively( $function, $data_array ) {
377 $response = [];
378 if ( is_array( $data_array ) ) {
379 if ( ! is_callable( $function ) ) {
380 return $data_array;
381 }
382 foreach ( $data_array as $key => $data ) {
383 $val = is_array( $data ) ? self::sanitize_recursively( $function, $data ) : $function( $data );
384 $response[ $key ] = $val;
385 }
386 }
387
388 return $response;
389 }
390
391 /**
392 * Generates common markup liked label, etc
393 *
394 * @param int|string $form_id form id.
395 * @param string $type Type of form markup.
396 * @param string $label Label for the form markup.
397 * @param string $slug Slug for the form markup.
398 * @param string $block_id Block id for the form markup.
399 * @param bool $required If field is required or not.
400 * @param string $help Help for the form markup.
401 * @param string $error_msg Error message for the form markup.
402 * @param bool $is_unique Check if the field is unique.
403 * @param string $duplicate_msg Duplicate message for field.
404 * @param bool $override Override for error markup.
405 * @return string
406 * @since 0.0.1
407 */
408 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 ) {
409 $duplicate_msg = $duplicate_msg ? ' data-unique-msg="' . esc_attr( $duplicate_msg ) . '"' : '';
410
411 $markup = '';
412 $show_labels_as_placeholder = get_post_meta( self::get_integer_value( $form_id ), '_srfm_use_label_as_placeholder', true );
413 $show_labels_as_placeholder = $show_labels_as_placeholder ? self::get_string_value( $show_labels_as_placeholder ) : false;
414
415 $required_sign = apply_filters( 'srfm_value_after_label_placeholder', ' *' );
416
417 if ( ! is_string( $required_sign ) ) {
418 $required_sign = ' *';
419 }
420
421 switch ( $type ) {
422 case 'label':
423 if ( $label ) {
424 ob_start();
425 ?>
426 <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">
427 <?php echo esc_html( $label ); ?>
428 <?php if ( $required ) { ?>
429 <span class="srfm-required" aria-hidden="true"> *</span>
430 <?php } ?>
431 </label>
432 <?php
433 $markup = ob_get_clean();
434 }
435 break;
436 case 'help':
437 if ( $help ) {
438 ob_start();
439 ?>
440 <div class="srfm-description" id="srfm-description-<?php echo esc_attr( $block_id ); ?>">
441 <?php echo esc_html( $help ); ?>
442 </div>
443 <?php
444 $markup = ob_get_clean();
445 }
446 break;
447 case 'error':
448 if ( $required || $override ) {
449 ob_start();
450 ?>
451 <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 ?>>
452 <?php echo esc_html( $error_msg ); ?>
453 </div>
454 <?php
455 $markup = ob_get_clean();
456 }
457 break;
458 case 'is_unique':
459 if ( $is_unique ) {
460 ob_start();
461 ?>
462 <div class="srfm-error">
463 <?php echo esc_html( $duplicate_msg ); ?>
464 </div>
465 <?php
466 $markup = ob_get_clean();
467 }
468 break;
469 case 'placeholder':
470 $markup = $label && '1' === $show_labels_as_placeholder ? esc_html( $label ) . ( $required ? esc_attr( $required_sign ) : '' ) : '';
471 break;
472 case 'label_text':
473 // This has been added for generating label text for the form markup instead of adding it in the label tag.
474 if ( $label ) {
475 ob_start();
476 ?>
477 <?php echo esc_html( $label ); ?>
478 <?php if ( $required ) { ?>
479 <span class="srfm-required" aria-hidden="true"> *</span>
480 <?php } ?>
481 <?php
482 $markup = ob_get_clean();
483 }
484 break;
485 default:
486 $markup = '';
487 }
488
489 return is_string( $markup ) ? $markup : '';
490 }
491
492 /**
493 * Get an SVG Icon
494 *
495 * @since 0.0.1
496 * @param string $icon the icon name.
497 * @param string $class if the baseline class should be added.
498 * @param string $html Custom attributes inside svg wrapper.
499 * @return string
500 */
501 public static function fetch_svg( $icon = '', $class = '', $html = '' ) {
502 $class = $class ? ' ' . $class : '';
503
504 if ( ! self::$srfm_svgs ) {
505 ob_start();
506
507 include_once SRFM_DIR . 'assets/svg/svgs.json';
508 self::$srfm_svgs = json_decode( self::get_string_value( ob_get_clean() ), true );
509 self::$srfm_svgs = apply_filters( 'srfm_svg_icons', self::$srfm_svgs );
510 }
511
512 ob_start();
513 ?>
514 <span class="srfm-icon<?php echo esc_attr( $class ); ?>" <?php echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>>
515 <?php echo self::$srfm_svgs[ $icon ] ?? ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
516 </span>
517 <?php
518 $output = ob_get_clean();
519 return is_string( $output ) ? $output : '';
520 }
521
522 /**
523 * Base64-encode a string for use inside a field key.
524 *
525 * Replaces encrypt(), which is retained as a deprecated alias. The encoding itself
526 * is unchanged since 0.0.1 — only the name is new.
527 *
528 * NOT ENCRYPTION. This is plain, unkeyed base64 (padding stripped) used only to
529 * carry a label inside a field key. There is no key, no HMAC and no integrity
530 * protection, so a value round-tripped through decode() is fully attacker-forgeable
531 * and must never be treated as authentic or trusted as a security boundary. When a
532 * label's integrity matters, look it up from the form's stored block definitions by
533 * block id instead of decoding it from the submitted key.
534 *
535 * Two behaviours worth knowing before relying on this pair:
536 *
537 * - The input is run through wp_strip_all_tags(), so this is not a lossless
538 * round trip: decode( encode( $x ) ) !== $x whenever $x contains markup.
539 * That stripping happens on this trusted side only — decode() returns raw
540 * submitted bytes and does NOT strip anything, so every sink must escape for
541 * its own context (esc_html(), escape_csv_formula(), ...).
542 * - Falsy input (including the string '0') returns '', not base64.
543 *
544 * @param string $input The input string to encode.
545 * @since 2.12.3
546 * @return string The base64-encoded string (padding removed).
547 */
548 public static function encode( $input ) {
549 // If the input is empty or not a string, then abandon ship.
550 if ( empty( $input ) || ! is_string( $input ) ) {
551 return '';
552 }
553
554 // Strip HTML tags to prevent them from being included in IDs and field names.
555 $input = wp_strip_all_tags( $input );
556
557 // Base64-encode the input and return it.
558 $base_64 = base64_encode( $input ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
559 return rtrim( $base_64, '=' );
560 }
561
562 /**
563 * Base64-encode a string.
564 *
565 * @deprecated 2.12.3 Use {@see self::encode()}. The name wrongly implied a security
566 * boundary — this is unkeyed base64, not encryption.
567 *
568 * @param string $input The input string to encode.
569 * @since 0.0.1
570 * @return string The base64-encoded string.
571 */
572 public static function encrypt( $input ) {
573 return self::encode( $input );
574 }
575
576 /**
577 * Base64-decode a string produced by encode().
578 *
579 * Replaces decrypt(), which is retained as a deprecated alias. The decoding itself
580 * is unchanged since 0.0.1 — only the name is new.
581 *
582 * NOT DECRYPTION. See {@see self::encode()} — the result is unauthenticated and
583 * attacker-forgeable; do not trust it where integrity matters. The output is raw
584 * submitted bytes: no tag stripping, no sanitising. Escape it at the sink.
585 *
586 * @param string $input The input string to decode.
587 * @since 2.12.3
588 * @return string The decoded string.
589 */
590 public static function decode( $input ) {
591 // If the input is empty or not a string, then abandon ship.
592 if ( empty( $input ) || ! is_string( $input ) ) {
593 return '';
594 }
595
596 // Base64-decode the input and return it.
597 $base_64 = $input . str_repeat( '=', strlen( $input ) % 4 );
598 return base64_decode( $base_64 ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
599 }
600
601 /**
602 * Base64-decode a string.
603 *
604 * @deprecated 2.12.3 Use {@see self::decode()}. The name wrongly implied a security
605 * boundary — this is unkeyed base64, not decryption.
606 *
607 * @param string $input The input string to decode.
608 * @since 0.0.1
609 * @return string The decoded string.
610 */
611 public static function decrypt( $input ) {
612 return self::decode( $input );
613 }
614
615 /**
616 * Update an option from the database.
617 *
618 * @param string $key The option key.
619 * @param mixed $value The value to update.
620 * @param bool $network_override Whether to allow the network_override admin setting to be overridden on subsites.
621 * @since 0.0.1
622 * @return bool True if the option was updated, false otherwise.
623 */
624 public static function update_admin_settings_option( $key, $value, $network_override = false ) {
625 // Update the site-wide option if we're in the network admin, and return the updated status.
626 return $network_override && is_multisite() ? update_site_option( $key, $value ) : update_option( $key, $value );
627 }
628
629 /**
630 * Update an option from the database.
631 *
632 * @param int|string $post_id post id / form id.
633 * @param string $key meta key name.
634 * @param bool $single single or multiple.
635 * @param mixed $default default value.
636 *
637 * @since 0.0.1
638 * @return string Meta value.
639 */
640 public static function get_meta_value( $post_id, $key, $single = true, $default = '' ) {
641 $srfm_live_mode_data = self::get_instant_form_live_data();
642
643 if ( isset( $srfm_live_mode_data[ $key ] ) ) {
644 // Give priority to live mode data if we have one set from the Instant Form.
645 return self::get_string_value( $srfm_live_mode_data[ $key ] );
646 }
647
648 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 );
649 }
650
651 /**
652 * Wrapper for the WordPress's get_post_meta function with the support for default values.
653 *
654 * @param int|string $post_id Post ID.
655 * @param string $key The meta key to retrieve.
656 * @param mixed $default Default value.
657 * @param bool $single Optional. Whether to return a single value.
658 * @since 0.0.8
659 * @return mixed Meta value.
660 */
661 public static function get_post_meta( $post_id, $key, $default = null, $single = true ) {
662 $meta_value = get_post_meta( self::get_integer_value( $post_id ), $key, $single );
663 return $meta_value ? $meta_value : $default;
664 }
665
666 /**
667 * Returns query params data for instant form live preview.
668 *
669 * @since 0.0.8
670 * @return array<mixed> Live preview data.
671 */
672 public static function get_instant_form_live_data() {
673 $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.
674
675 return $srfm_live_mode_data ? array_map(
676 // Normalize falsy values.
677 static function( $live_data ) {
678 return 'false' === $live_data ? false : $live_data;
679 },
680 $srfm_live_mode_data
681 ) : [];
682 }
683
684 /**
685 * Default dynamic block value.
686 *
687 * @since 0.0.1
688 * @return array<string> Meta value.
689 */
690 public static function default_dynamic_block_option() {
691
692 $common_err_msg = self::get_common_err_msg();
693
694 $default_values = [
695 'srfm_url_block_required_text' => $common_err_msg['required'],
696 'srfm_input_block_required_text' => $common_err_msg['required'],
697 'srfm_input_block_unique_text' => $common_err_msg['unique'],
698 'srfm_address_block_required_text' => $common_err_msg['required'],
699 'srfm_phone_block_required_text' => $common_err_msg['required'],
700 'srfm_phone_block_unique_text' => $common_err_msg['unique'],
701 'srfm_number_block_required_text' => $common_err_msg['required'],
702 'srfm_textarea_block_required_text' => $common_err_msg['required'],
703 'srfm_multi_choice_block_required_text' => $common_err_msg['required'],
704 'srfm_checkbox_block_required_text' => $common_err_msg['required'],
705 'srfm_gdpr_block_required_text' => $common_err_msg['required'],
706 'srfm_email_block_required_text' => $common_err_msg['required'],
707 'srfm_email_block_unique_text' => $common_err_msg['unique'],
708 'srfm_dropdown_block_required_text' => $common_err_msg['required'],
709 'srfm_rating_block_required_text' => $common_err_msg['required'],
710 ];
711
712 $default_values = array_merge( $default_values, Translatable::dynamic_validation_messages() );
713
714 return apply_filters( 'srfm_default_dynamic_block_option', $default_values, $common_err_msg );
715 }
716
717 /**
718 * Get default dynamic block value.
719 *
720 * @param string $key meta key name.
721 * @since 0.0.1
722 * @return string Meta value.
723 */
724 public static function get_default_dynamic_block_option( $key ) {
725 $default_dynamic_values = self::default_dynamic_block_option();
726 $option = get_option( 'srfm_default_dynamic_block_option', $default_dynamic_values );
727
728 if ( is_array( $option ) && array_key_exists( $key, $option ) ) {
729 return $option[ $key ];
730 }
731 return '';
732 }
733
734 /**
735 * Checks whether a given request has appropriate permissions.
736 *
737 * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
738 * @since 0.0.1
739 */
740 public static function get_items_permissions_check() {
741 if ( self::current_user_can() ) {
742 return true;
743 }
744
745 return new WP_Error(
746 'rest_cannot_view',
747 __( 'Sorry, you are not allowed to perform this action.', 'sureforms' ),
748 [ 'status' => \rest_authorization_required_code() ]
749 );
750 }
751
752 /**
753 * Check if the current user has a given capability.
754 *
755 * @param string $capability The capability to check.
756 * @param array<mixed> $args Optional. Additional arguments to pass to the capability check.
757 *
758 * @since 0.0.3
759 * @return bool Whether the current user has the given capability or role.
760 */
761 public static function current_user_can( $capability = '', $args = [] ) {
762 if ( ! function_exists( 'current_user_can' ) ) {
763 return false;
764 }
765
766 if ( ! is_string( $capability ) || empty( $capability ) ) {
767 $capability = 'manage_options';
768 }
769
770 return ! empty( $args ) && is_array( $args ) && count( $args ) > 0
771 ? current_user_can( $capability, ...$args )
772 : current_user_can( $capability );
773 }
774
775 /**
776 * Get all the entries for the given form ids. The entries are older than the given days_old.
777 *
778 * @param int $days_old The number of days old the entries should be.
779 * @param array<int> $sf_form_ids The form ids for which the entries need to be fetched.
780 * @since 0.0.2
781 * @return array<mixed> the entries matching the criteria.
782 */
783 public static function get_entries_from_form_ids( $days_old = 0, $sf_form_ids = [] ) {
784
785 $entries = [];
786 $days_old_date = ( new \DateTime() )->modify( "-{$days_old} days" )->format( 'Y-m-d H:i:s' );
787
788 foreach ( $sf_form_ids as $form_id ) {
789 // args according to the get_all() function in the Entries class.
790 $args = [
791 'where' => [
792 [
793 [
794 'key' => 'form_id',
795 'value' => $form_id,
796 'compare' => '=',
797 ],
798 [
799 'key' => 'created_at',
800 'value' => $days_old_date,
801 'compare' => '<=',
802 ],
803 ],
804 ],
805 ];
806
807 // store all the entries in a single array.
808 $entries = array_merge( $entries, Entries::get_all( $args, false ) );
809 }
810 return $entries;
811 }
812
813 /**
814 * Decode block attributes.
815 * The function reverses the effect of serialize_block_attributes()
816 *
817 * @link https://developer.wordpress.org/reference/functions/serialize_block_attributes/
818 * @param string $encoded_data the encoded block attribute.
819 * @since 0.0.2
820 * @return string decoded block attribute
821 */
822 public static function decode_block_attribute( $encoded_data = '' ) {
823 $decoded_data = preg_replace( '/\\\\u002d\\\\u002d/', '--', self::get_string_value( $encoded_data ) );
824 $decoded_data = preg_replace( '/\\\\u003c/', '<', self::get_string_value( $decoded_data ) );
825 $decoded_data = preg_replace( '/\\\\u003e/', '>', self::get_string_value( $decoded_data ) );
826 $decoded_data = preg_replace( '/\\\\u0026/', '&', self::get_string_value( $decoded_data ) );
827 $decoded_data = preg_replace( '/\\\\\\\\"/', '"', self::get_string_value( $decoded_data ) );
828 return self::get_string_value( $decoded_data );
829 }
830
831 /**
832 * Map slugs to submission data.
833 *
834 * @param array<mixed> $submission_data submission_data.
835 * @since 0.0.3
836 * @return array<mixed>
837 */
838 public static function map_slug_to_submission_data( $submission_data = [] ) {
839 $mapped_data = [];
840 foreach ( $submission_data as $key => $value ) {
841 if ( false === strpos( $key, '-lbl-' ) ) {
842 continue;
843 }
844 $label = explode( '-lbl-', $key )[1];
845 $slug = implode( '-', array_slice( explode( '-', $label ), 1 ) );
846 $slug = str_replace( ' ', '_', $slug );
847
848 /**
849 * Filters whether a field should be skipped when mapping slugs to submission data.
850 *
851 * This filter allows plugins or custom code to determine if a field should be excluded
852 * from the mapped submission data array (such as for internal fields or extraneous meta).
853 *
854 * @since 2.0.0
855 *
856 * @param bool $skip_this_field Whether to skip this field from processing. Default false.
857 * @param array $args {
858 * Arguments used for this field.
859 *
860 * @type string $key The original key of the field in the submission data array.
861 * @type string $slug The mapped slug parsed from the field key.
862 * @type mixed $value The value assigned to this field.
863 * }
864 */
865 $skip_this_field = apply_filters(
866 'srfm_map_slug_to_submission_data_should_skip',
867 false,
868 [
869 'key' => $key,
870 'slug' => $slug,
871 'value' => $value,
872 ]
873 );
874
875 if ( $skip_this_field ) {
876 continue;
877 }
878
879 // Check if value is array to handle external package field functionality.
880 // like repeater fields that need special processing.
881 if ( is_array( $value ) && ! empty( $value ) ) {
882 // Apply filter to allow external packages to process array values.
883 // Returns processed data with 'is_processed' flag if successfully handled.
884 $filtered_submission_data = apply_filters(
885 'srfm_map_slug_to_submission_data_array',
886 [
887 'value' => $value,
888 'key' => $key,
889 'slug' => $slug,
890 ]
891 );
892 if ( isset( $filtered_submission_data['is_processed'] ) && true === $filtered_submission_data['is_processed'] ) {
893 $mapped_data[ $slug ] = $filtered_submission_data['value'];
894 continue;
895 }
896 }
897
898 // If the value is an array (e.g. multi-upload field), decode each URL value.
899 if ( is_array( $value ) ) {
900 $mapped_data[ $slug ] = array_map(
901 static function ( $val ) {
902 return is_string( $val ) ? rawurldecode( $val ) : $val;
903 },
904 $value
905 );
906 continue;
907 }
908
909 $mapped_data[ $slug ] = is_string( $value ) ? html_entity_decode( esc_attr( $value ) ) : $value;
910 }
911 return $mapped_data;
912 }
913
914 /**
915 * Get forms options. Shows all the available forms in the dropdown.
916 *
917 * @since 0.0.5
918 * @param string $key Determines the type of data to return.
919 * @return array<mixed>
920 */
921 public static function get_sureforms( $key = '' ) {
922 $forms = get_posts(
923 apply_filters(
924 'srfm_get_sureforms_query_args',
925 [
926 'post_type' => SRFM_FORMS_POST_TYPE,
927 'posts_per_page' => -1,
928 'post_status' => 'publish',
929 ]
930 )
931 );
932
933 $options = [];
934
935 foreach ( $forms as $form ) {
936 if ( $form instanceof WP_Post ) {
937 if ( 'all' === $key ) {
938 $options[ $form->ID ] = $form;
939 } elseif ( ! empty( $key ) && is_string( $key ) && isset( $form->$key ) ) {
940 $options[ $form->ID ] = $form->$key;
941 } else {
942 $options[ $form->ID ] = $form->post_title;
943 }
944 }
945 }
946
947 return $options;
948 }
949
950 /**
951 * Get all the forms.
952 *
953 * @since 0.0.5
954 * @return array<mixed>
955 */
956 public static function get_sureforms_title_with_ids() {
957 $form_options = self::get_sureforms();
958
959 foreach ( $form_options as $key => $value ) {
960 $form_options[ $key ] = $value . ' #' . $key;
961 }
962
963 return $form_options;
964 }
965
966 /**
967 * Get the CSS variables based on different field spacing sizes.
968 *
969 * @param string|null $field_spacing The field spacing size or boolean false to return complete sizes array.
970 *
971 * @since 0.0.7
972 * @return array<string|mixed>
973 */
974 public static function get_css_vars( $field_spacing = null ) {
975 /**
976 * $sizes - Field Spacing Sizes Variables.
977 * The array contains the CSS variables for different field spacing sizes.
978 * Each key corresponds to the field spacing size, and the value is an array of CSS variables.
979 *
980 * For future variables depending on the field spacing size, add the variable to the array respectively.
981 */
982 $sizes = apply_filters(
983 'srfm_css_vars_sizes',
984 [
985 'small' => [
986 '--srfm-row-gap-between-blocks' => '16px',
987 // Address block gap and spacing variables.
988 '--srfm-address-label-font-size' => '14px',
989 '--srfm-address-label-line-height' => '20px',
990 '--srfm-address-description-font-size' => '12px',
991 '--srfm-address-description-line-height' => '16px',
992 '--srfm-col-gap-between-fields' => '12px',
993 '--srfm-row-gap-between-fields' => '12px',
994 '--srfm-gap-below-address-label' => '12px',
995 // Dropdown Variables.
996 '--srfm-dropdown-font-size' => '14px',
997 '--srfm-dropdown-gap-between-input-menu' => '4px',
998 '--srfm-dropdown-badge-padding' => '2px 6px',
999 '--srfm-dropdown-multiselect-font-size' => '12px',
1000 '--srfm-dropdown-multiselect-line-height' => '16px',
1001 '--srfm-dropdown-padding-right' => '12px',
1002 // initial padding and from 20px - 12px for dropdown arrow width and 8px for gap before dropdown arrow.
1003 '--srfm-dropdown-padding-right-icon' => 'calc( var( --srfm-dropdown-padding-right ) + 20px )',
1004 '--srfm-dropdown-multiselect-padding' => '8px var( --srfm-dropdown-padding-right-icon ) 8px 8px',
1005 // Input Field Variables.
1006 '--srfm-input-height' => '40px',
1007 '--srfm-input-field-padding' => '10px 12px',
1008 '--srfm-input-field-font-size' => '14px',
1009 '--srfm-input-field-line-height' => '20px',
1010 '--srfm-input-field-margin-top' => '4px',
1011 '--srfm-input-field-margin-bottom' => '4px',
1012 // Checkbox and GDPR Variables.
1013 '--srfm-checkbox-label-font-size' => '14px',
1014 '--srfm-checkbox-label-line-height' => '20px',
1015 '--srfm-checkbox-description-font-size' => '12px',
1016 '--srfm-checkbox-description-line-height' => '16px',
1017 '--srfm-check-ctn-width' => '16px',
1018 '--srfm-check-ctn-height' => '16px',
1019 '--srfm-check-svg-size' => '10px',
1020 '--srfm-checkbox-margin-top-frontend' => '2px',
1021 '--srfm-checkbox-margin-top-editor' => '3px',
1022 '--srfm-check-gap' => '8px',
1023 '--srfm-checkbox-description-margin-left' => '24px',
1024 // Phone Number field variables.
1025 '--srfm-flag-section-padding' => '10px 0 10px 12px',
1026 '--srfm-gap-between-icon-text' => '8px',
1027 // Label Variables.
1028 '--srfm-label-font-size' => '14px',
1029 '--srfm-label-line-height' => '20px',
1030 // Description Variables.
1031 '--srfm-description-font-size' => '12px',
1032 '--srfm-description-line-height' => '16px',
1033 // Button Variables.
1034 '--srfm-btn-padding' => '8px 14px',
1035 '--srfm-btn-font-size' => '14px',
1036 '--srfm-btn-line-height' => '20px',
1037 // Multi Choice Variables.
1038 '--srfm-multi-choice-horizontal-padding' => '16px',
1039 '--srfm-multi-choice-vertical-padding' => '16px',
1040 '--srfm-multi-choice-internal-option-gap' => '8px',
1041 '--srfm-multi-choice-vertical-svg-size' => '32px',
1042 '--srfm-multi-choice-horizontal-image-size' => '20px',
1043 '--srfm-multi-choice-vertical-image-size' => '100px',
1044 '--srfm-multi-choice-outer-padding' => '0',
1045 ],
1046 'medium' => [
1047 '--srfm-row-gap-between-blocks' => '18px',
1048 // Address block gap and spacing variables.
1049 '--srfm-address-label-font-size' => '16px',
1050 '--srfm-address-label-line-height' => '24px',
1051 '--srfm-address-description-font-size' => '14px',
1052 '--srfm-address-description-line-height' => '20px',
1053 '--srfm-col-gap-between-fields' => '16px',
1054 '--srfm-row-gap-between-fields' => '16px',
1055 '--srfm-gap-below-address-label' => '14px',
1056 // Input Field Variables.
1057 '--srfm-input-height' => '44px',
1058 '--srfm-input-field-font-size' => '16px',
1059 '--srfm-input-field-line-height' => '24px',
1060 '--srfm-input-field-margin-top' => '6px',
1061 '--srfm-input-field-margin-bottom' => '6px',
1062 // Checkbox and GDPR Variables.
1063 '--srfm-checkbox-label-font-size' => '16px',
1064 '--srfm-checkbox-label-line-height' => '24px',
1065 '--srfm-checkbox-description-font-size' => '14px',
1066 '--srfm-checkbox-description-line-height' => '20px',
1067 '--srfm-checkbox-margin-top-frontend' => '4px',
1068 '--srfm-checkbox-margin-top-editor' => '6px',
1069 '--srfm-checkbox-description-margin-left' => '24px',
1070 // Label Variables.
1071 '--srfm-label-font-size' => '16px',
1072 '--srfm-label-line-height' => '24px',
1073 // Description Variables.
1074 '--srfm-description-font-size' => '14px',
1075 '--srfm-description-line-height' => '20px',
1076 // Button Variables.
1077 '--srfm-btn-padding' => '10px 14px',
1078 '--srfm-btn-font-size' => '16px',
1079 '--srfm-btn-line-height' => '24px',
1080 // Multi Choice Variables.
1081 '--srfm-multi-choice-horizontal-padding' => '20px',
1082 '--srfm-multi-choice-vertical-padding' => '20px',
1083 '--srfm-multi-choice-vertical-svg-size' => '40px',
1084 '--srfm-multi-choice-horizontal-image-size' => '24px',
1085 '--srfm-multi-choice-vertical-image-size' => '120px',
1086 '--srfm-multi-choice-outer-padding' => '2px',
1087 ],
1088 'large' => [
1089 '--srfm-row-gap-between-blocks' => '20px',
1090 // Address Block Gap and Spacing Variables.
1091 '--srfm-address-label-font-size' => '18px',
1092 '--srfm-address-label-line-height' => '28px',
1093 '--srfm-address-description-font-size' => '16px',
1094 '--srfm-address-description-line-height' => '24px',
1095 '--srfm-col-gap-between-fields' => '16px',
1096 '--srfm-row-gap-between-fields' => '20px',
1097 '--srfm-gap-below-address-label' => '16px',
1098 // Dropdown Variables.
1099 '--srfm-dropdown-font-size' => '16px',
1100 '--srfm-dropdown-gap-between-input-menu' => '6px',
1101 '--srfm-dropdown-badge-padding' => '6px 6px',
1102 '--srfm-dropdown-multiselect-font-size' => '14px',
1103 '--srfm-dropdown-multiselect-line-height' => '20px',
1104 '--srfm-dropdown-padding-right' => '14px',
1105 // Input Field Variables.
1106 '--srfm-input-height' => '48px',
1107 '--srfm-input-field-padding' => '10px 14px',
1108 '--srfm-input-field-font-size' => '18px',
1109 '--srfm-input-field-line-height' => '28px',
1110 '--srfm-input-field-margin-top' => '8px',
1111 '--srfm-input-field-margin-bottom' => '8px',
1112 // Checkbox and GDPR Variables.
1113 '--srfm-checkbox-label-font-size' => '18px',
1114 '--srfm-checkbox-label-line-height' => '28px',
1115 '--srfm-checkbox-description-font-size' => '16px',
1116 '--srfm-checkbox-description-line-height' => '24px',
1117 '--srfm-check-ctn-width' => '20px',
1118 '--srfm-check-ctn-height' => '20px',
1119 '--srfm-check-svg-size' => '14px',
1120 '--srfm-check-gap' => '10px',
1121 '--srfm-checkbox-margin-top-frontend' => '4px',
1122 '--srfm-checkbox-margin-top-editor' => '5px',
1123 '--srfm-checkbox-description-margin-left' => '30px',
1124 // Label Variables.
1125 '--srfm-label-font-size' => '18px',
1126 '--srfm-label-line-height' => '28px',
1127 // Description Variables.
1128 '--srfm-description-font-size' => '16px',
1129 '--srfm-description-line-height' => '24px',
1130 // Button Variables.
1131 '--srfm-btn-padding' => '10px 14px',
1132 '--srfm-btn-font-size' => '18px',
1133 '--srfm-btn-line-height' => '28px',
1134 // Multi Choice Variables.
1135 '--srfm-multi-choice-horizontal-padding' => '24px',
1136 '--srfm-multi-choice-vertical-padding' => '24px',
1137 '--srfm-multi-choice-internal-option-gap' => '12px',
1138 '--srfm-multi-choice-vertical-svg-size' => '48px',
1139 '--srfm-multi-choice-horizontal-image-size' => '28px',
1140 '--srfm-multi-choice-vertical-image-size' => '140px',
1141 '--srfm-multi-choice-outer-padding' => '4px',
1142 ],
1143 ]
1144 );
1145 // Return complete sizes array if field_spacing is false. Required in case of JS for Editor changes.
1146 if ( ! $field_spacing ) {
1147 return $sizes;
1148 }
1149
1150 $selected_size = $sizes['small'];
1151 if ( 'small' !== $field_spacing && isset( $sizes[ $field_spacing ] ) ) {
1152 $selected_size = array_merge( $selected_size, $sizes[ $field_spacing ] );
1153 }
1154
1155 return $selected_size;
1156 }
1157
1158 /**
1159 * Array of SureForms blocks which get have user input.
1160 *
1161 * @since 0.0.10
1162 * @return array<string>
1163 */
1164 public static function get_sureforms_blocks() {
1165 return apply_filters(
1166 'srfm_blocks',
1167 [
1168 'srfm/input',
1169 'srfm/email',
1170 'srfm/textarea',
1171 'srfm/number',
1172 'srfm/checkbox',
1173 'srfm/gdpr',
1174 'srfm/phone',
1175 'srfm/address',
1176 'srfm/dropdown',
1177 'srfm/multi-choice',
1178 'srfm/radio',
1179 'srfm/submit',
1180 'srfm/url',
1181 'srfm/payment',
1182 ]
1183 );
1184 }
1185
1186 /**
1187 * Render a site key missing error message.
1188 *
1189 * @param string $provider_name Name of the captcha provider (e.g., HCaptcha, Google reCAPTCHA, Turnstile).
1190 * @since 1.7.0
1191 * @since 1.7.1 moved to inc/helper.php from inc/generate-form-markup.php
1192 * @return void
1193 */
1194 public static function render_missing_sitekey_error( $provider_name ) {
1195 $icon = self::fetch_svg( 'info_circle', '', 'aria-hidden="true"' );
1196 ?>
1197 <p id="sitekey-error" class="srfm-common-error-message srfm-error-message">
1198 <?php echo wp_kses( $icon, self::$allowed_tags_svg ); ?>
1199 <span class="srfm-error-content">
1200 <?php
1201 echo esc_html(
1202 sprintf(
1203 /* translators: %s: Provider name like HCaptcha, Google reCAPTCHA, Turnstile */
1204 __( '%s sitekey is missing. Please contact your site administrator.', 'sureforms' ),
1205 $provider_name
1206 )
1207 );
1208 ?>
1209 </span>
1210 </p>
1211 <?php
1212 }
1213
1214 /**
1215 * Parse and sanitize an email list string which may contain:
1216 *
1217 * @param string $input email addresses.
1218 * @since 1.13.2
1219 * @return string Sanitized email header string.
1220 */
1221 public static function sanitize_email_header( $input ) {
1222 if ( empty( $input ) ) {
1223 return '';
1224 }
1225
1226 $parts = explode( ',', $input );
1227 $output = [];
1228
1229 foreach ( $parts as $part ) {
1230 $part = trim( $part );
1231
1232 // Match "Name <email>".
1233 if ( preg_match( '/^(.*)<(.+)>$/', $part, $matches ) ) {
1234 $name = trim( $matches[1], "\" \t\n\r\0\x0B" ); // trim quotes.
1235 $email = sanitize_email( trim( $matches[2] ) );
1236
1237 if ( is_email( $email ) ) {
1238 $safe_name = sanitize_text_field( $name );
1239 $output[] = $safe_name . ' <' . $email . '>';
1240 }
1241 } else {
1242 // Plain email case.
1243 $email = sanitize_email( $part );
1244 if ( is_email( $email ) ) {
1245 $output[] = $email;
1246 }
1247 }
1248 }
1249
1250 return ! empty( $output ) ? implode( ', ', $output ) : '';
1251 }
1252
1253 /**
1254 * Process blocks and inner blocks.
1255 *
1256 * @param array<mixed> $blocks The block data.
1257 * @param array<string> $slugs The array of existing slugs.
1258 * @param bool $updated The array of existing slugs.
1259 * @param string $prefix The array of existing slugs.
1260 * @param bool $skip_checking_existing_slug Skips the checking of existing slug if passed true. More information documented inside this function.
1261 * @since 0.0.10
1262 * @return array
1263 */
1264 public static function process_blocks( $blocks, &$slugs, &$updated, $prefix = '', $skip_checking_existing_slug = false ) {
1265
1266 if ( ! is_array( $blocks ) ) {
1267 return [ $blocks, $slugs, $updated ];
1268 }
1269
1270 foreach ( $blocks as $index => $block ) {
1271
1272 if ( ! is_array( $block ) ) {
1273 continue;
1274 }
1275 // Checking only for SureForms blocks which can have user input.
1276 if ( empty( $block['blockName'] ) || ! in_array( $block['blockName'], self::get_sureforms_blocks(), true ) ) {
1277 continue;
1278 }
1279
1280 /**
1281 * Lets continue if slug already exists.
1282 * This will ensure that we don't update already existing slugs.
1283 */
1284 if ( isset( $block['attrs'] ) && ! empty( $block['attrs']['slug'] ) && ! in_array( $block['attrs']['slug'], $slugs, true ) ) {
1285
1286 // Made it associative array, so that we can directly check it using block_id rather than mapping or using "in_array" for the checks.
1287 $slugs[ $block['attrs']['block_id'] ] = self::get_string_value( $block['attrs']['slug'] );
1288
1289 if ( is_array( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) ) {
1290 [ $blocks[ $index ]['innerBlocks'], $slugs, $updated ] = self::process_blocks( $block['innerBlocks'], $slugs, $updated, '' );
1291 }
1292 continue;
1293 }
1294
1295 if ( $skip_checking_existing_slug && empty( $block['innerBlocks'] ) && isset( $slugs[ $block['attrs']['block_id'] ] ) ) {
1296 /**
1297 * Skip re-processing of the already process or existing slugs if above parameter "$skip_checking_existing_slug" is passed as true.
1298 * This is helpful in the scenarios where we need to compare and verify between already saved blocks and new unsaved blocks parsed
1299 * from the contents.
1300 *
1301 * However, it is also necessary to make sure if that current block is not a parent / wrapper block
1302 * by checking "$block['innerBlocks']" empty.
1303 *
1304 * And finally, checking if the block-id "$block['attrs']['block_id']" is already set in the list of "$slugs",
1305 * making sure that we are only processing the new blocks.
1306 */
1307 continue;
1308 }
1309
1310 if ( is_array( $blocks[ $index ]['attrs'] ) ) {
1311
1312 $blocks[ $index ]['attrs']['slug'] = self::generate_unique_block_slug( $block, $slugs, $prefix );
1313 $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.
1314 $updated = true;
1315 if ( is_array( $block['innerBlocks'] ) && ! empty( $block['innerBlocks'] ) ) {
1316
1317 [ $blocks[ $index ]['innerBlocks'], $slugs, $updated ] = self::process_blocks( $block['innerBlocks'], $slugs, $updated, $blocks[ $index ]['attrs']['slug'] );
1318
1319 }
1320 }
1321 }
1322 return [ $blocks, $slugs, $updated ];
1323 }
1324
1325 /**
1326 * Generates slug based on the provided block and existing slugs.
1327 *
1328 * @param array<mixed> $block The block data.
1329 * @param array<string> $slugs The array of existing slugs.
1330 * @param string $prefix The array of existing slugs.
1331 * @since 0.0.10
1332 * @return string The generated unique block slug.
1333 */
1334 public static function generate_unique_block_slug( $block, $slugs, $prefix ) {
1335 $slug = is_string( $block['blockName'] ) ? $block['blockName'] : '';
1336
1337 if ( ! empty( $block['attrs']['label'] ) && is_string( $block['attrs']['label'] ) ) {
1338 $slug = sanitize_title( $block['attrs']['label'] );
1339
1340 // If the label contains non-Latin characters (e.g. Japanese, Chinese),
1341 // sanitize_title() produces a percent-encoded slug like "%e3%83%95%e3%83%aa".
1342 // These are unstable and break conditional logic field matching.
1343 // Fall back to the block name to ensure a stable ASCII slug.
1344 if ( false !== strpos( $slug, '%' ) ) {
1345 $block_name = is_string( $block['blockName'] ) ? $block['blockName'] : '';
1346 // Strip the 'srfm/' namespace to match JS-side cleanForSlug() output.
1347 $block_name = (string) preg_replace( '/^srfm\//', '', $block_name );
1348 $slug = sanitize_title( $block_name );
1349 }
1350 }
1351
1352 if ( ! empty( $prefix ) ) {
1353 $slug = $prefix . '-' . $slug;
1354 }
1355
1356 return self::generate_slug( $slug, $slugs );
1357 }
1358
1359 /**
1360 * This function ensures that the slug is unique.
1361 * If the slug is already taken, it appends a number to the slug to make it unique.
1362 *
1363 * @param string $slug test to be converted to slug.
1364 * @param array<string> $slugs An array of existing slugs.
1365 * @since 0.0.10
1366 * @return string The unique slug.
1367 */
1368 public static function generate_slug( $slug, $slugs ) {
1369 $slug = sanitize_title( $slug );
1370
1371 if ( ! in_array( $slug, $slugs, true ) ) {
1372 return $slug;
1373 }
1374
1375 $index = 1;
1376
1377 while ( in_array( $slug . '-' . $index, $slugs, true ) ) {
1378 $index++;
1379 }
1380
1381 return $slug . '-' . $index;
1382 }
1383
1384 /**
1385 * Encode data to JSON. This function will encode the data with JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE.
1386 *
1387 * @since 0.0.11
1388 * @param array<mixed> $data The data to encode.
1389 * @return string|false The JSON representation of the value on success or false on failure.
1390 */
1391 public static function encode_json( $data ) {
1392 return wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
1393 }
1394
1395 /**
1396 * Returns true if SureTriggers plugin is ready for the custom app.
1397 *
1398 * @since 1.0.3
1399 * @return bool Returns true if SureTriggers plugin is ready for the custom app.
1400 */
1401 public static function is_suretriggers_ready() {
1402 if ( ! defined( 'SURE_TRIGGERS_FILE' ) ) {
1403 // Probably plugin is de-activated or not installed at all.
1404 return false;
1405 }
1406
1407 $suretriggers_data = get_option( 'suretrigger_options', [] );
1408 if ( ! is_array( $suretriggers_data ) || empty( $suretriggers_data['secret_key'] ) || ! is_string( $suretriggers_data['secret_key'] ) ) {
1409 // SureTriggers is not authenticated yet.
1410 return false;
1411 }
1412
1413 return true;
1414 }
1415
1416 /**
1417 * Registers script translations for a specific handle.
1418 *
1419 * This function sets the script translations for a given script handle, allowing
1420 * localization of JavaScript strings using the specified text domain and path.
1421 *
1422 * @param string $handle The script handle to apply translations to.
1423 * @param string $domain Optional. The text domain for translations. Default is 'sureforms'.
1424 * @param string $path Optional. The path to the translation files. Default is the 'languages' folder in the SureForms directory.
1425 *
1426 * @since 1.0.5
1427 * @return void
1428 */
1429 public static function register_script_translations( $handle, $domain = 'sureforms', $path = SRFM_DIR . 'languages' ) {
1430 wp_set_script_translations( $handle, $domain, $path );
1431 }
1432
1433 /**
1434 * Validates whether the specified conditions or a single key-value pair exist in the request context.
1435 *
1436 * - If `$conditions` is provided as an array, it will validate all key-value pairs in `$conditions`
1437 * against the `$_REQUEST` superglobal.
1438 * - If `$conditions` is empty, it validates a single key-value pair from `$key` and `$value`.
1439 *
1440 * @param string $value The expected value to match in the request if `$conditions` is not used.
1441 * @param string $key The key to check for in the request if `$conditions` is not used.
1442 * @param array<string, string> $conditions An optional associative array of key-value pairs to validate.
1443 * @since 1.1.1
1444 * @return bool Returns true if all conditions are met or the single key-value pair is valid, otherwise false.
1445 */
1446 public static function validate_request_context( $value, $key = 'post_type', $conditions = [] ) {
1447 // If conditions are provided, validate all key-value pairs in the conditions array.
1448 if ( ! empty( $conditions ) ) {
1449 foreach ( $conditions as $condition_key => $condition_value ) {
1450 if ( ! isset( $_REQUEST[ $condition_key ] ) || $_REQUEST[ $condition_key ] !== $condition_value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is a controlled comparison of request values.
1451 // Return false if any condition is not satisfied.
1452 return false;
1453 }
1454 }
1455 // Return true if all conditions are satisfied.
1456 return true;
1457 }
1458
1459 // Validate $value and $key when no conditions are provided.
1460 if ( empty( $key ) || empty( $value ) ) {
1461 return false;
1462 }
1463
1464 // Validate a single key-value pair when no conditions are provided.
1465 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.
1466 }
1467
1468 /**
1469 * Retrieve the list of excluded fields for form data processing.
1470 *
1471 * This method returns an array of field keys that should be excluded when
1472 * processing form data.
1473 *
1474 * @since 1.1.1
1475 * @return array<string> Returns the string array of excluded fields.
1476 */
1477 public static function get_excluded_fields() {
1478 $excluded_fields = [ 'srfm-honeypot-field', 'g-recaptcha-response', 'srfm-sender-email-field', 'form-id' ];
1479
1480 return apply_filters( 'srfm_excluded_fields', $excluded_fields );
1481 }
1482
1483 /**
1484 * Check whether the current page is a SureForms admin page.
1485 *
1486 * @since 1.2.2
1487 * @return bool Returns true if the current page is a SureForms admin page, otherwise false.
1488 */
1489 public static function is_sureforms_admin_page() {
1490 $current_screen = get_current_screen();
1491 $is_screen_sureforms_menu = self::validate_request_context( 'sureforms_menu', 'page' );
1492 $is_screen_add_new_form = self::validate_request_context( 'add-new-form', 'page' );
1493 $is_screen_sureforms_form_settings = self::validate_request_context( 'sureforms_form_settings', 'page' );
1494 $is_screen_sureforms_entries = self::validate_request_context( SRFM_ENTRIES, 'page' );
1495 $is_post_type_sureforms_form = $current_screen && SRFM_FORMS_POST_TYPE === $current_screen->post_type;
1496
1497 return $is_screen_sureforms_menu || $is_screen_add_new_form || $is_screen_sureforms_form_settings || $is_screen_sureforms_entries || $is_post_type_sureforms_form;
1498 }
1499
1500 /**
1501 * Filters and concatenates valid class names from an array.
1502 *
1503 * @param array<string> $class_names The array containing potential class names.
1504 * @since 1.4.0
1505 * @return string The concatenated string of valid class names separated by spaces.
1506 */
1507 public static function join_strings( $class_names ) {
1508 // Filter the array to include only valid class names.
1509 $valid_class_names = array_filter(
1510 $class_names,
1511 static function ( $value ) {
1512 return is_string( $value ) && '' !== $value && false !== $value;
1513 }
1514 );
1515
1516 // Concatenate the valid class names with spaces and return.
1517 return implode( ' ', $valid_class_names );
1518 }
1519 /**
1520 * Get SureForms Website URL.
1521 *
1522 * @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.
1523 * @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'].
1524 * @since 0.0.7
1525 * @return string
1526 */
1527 public static function get_sureforms_website_url( $trail, $utm_args = [] ) {
1528 $url = SRFM_WEBSITE;
1529 if ( ! empty( $trail ) && is_string( $trail ) ) {
1530 $url = SRFM_WEBSITE . $trail;
1531 }
1532
1533 if ( ! is_array( $utm_args ) ) {
1534 $utm_args = [];
1535 }
1536
1537 // SRFM-2709: deterministic UTM attribution — start.
1538 // When the caller opts into UTM tracking by passing any utm_args, fill in
1539 // SureForms' deterministic source/campaign defaults. Caller-provided keys
1540 // (including the placement passed via utm_medium) always win.
1541 if ( ! empty( $utm_args ) ) {
1542 $utm_args = array_merge(
1543 [
1544 'utm_source' => 'sureforms_plugin',
1545 'utm_campaign' => 'core_plugin',
1546 ],
1547 $utm_args
1548 );
1549 }
1550 // SRFM-2709: deterministic UTM attribution — end.
1551
1552 if ( class_exists( 'BSF_UTM_Analytics' ) ) {
1553 $url = \BSF_UTM_Analytics::get_utm_ready_link( $url, 'sureforms', $utm_args );
1554 }
1555
1556 // SRFM-2709: post-BSF_UTM_Analytics fallback — start.
1557 // BSF_UTM_Analytics returns the URL unchanged when no install referer is
1558 // recorded. Merge any caller UTM keys still missing from the final URL.
1559 if ( ! empty( $utm_args ) ) {
1560 $existing = [];
1561 $query = wp_parse_url( $url, PHP_URL_QUERY );
1562 if ( is_string( $query ) && '' !== $query ) {
1563 parse_str( $query, $existing );
1564 }
1565 $missing = array_diff_key( $utm_args, $existing );
1566 if ( ! empty( $missing ) ) {
1567 $url = add_query_arg( $missing, $url );
1568 }
1569 }
1570 // SRFM-2709: post-BSF_UTM_Analytics fallback — end.
1571
1572 return esc_url( $url );
1573 }
1574
1575 /**
1576 * Validates if the given string is a valid CSS class name.
1577 *
1578 * A valid CSS class name:
1579 * - Does not start with a digit, hyphen, or underscore.
1580 * - Can contain alphanumeric characters, underscores, hyphens, and Unicode letters.
1581 *
1582 * @param string $class_name The class name to validate.
1583 *
1584 * @since 1.3.1
1585 * @return bool True if the class name is valid, otherwise false.
1586 */
1587 public static function is_valid_css_class_name( $class_name ) {
1588 // Regular expression to validate a Unicode-aware CSS class name.
1589 $class_name_regex = '/^[^\d\-_][\w\p{L}\p{N}\-_]*$/u';
1590
1591 // Check if the className matches the pattern.
1592 return preg_match( $class_name_regex, $class_name ) === 1;
1593 }
1594
1595 /**
1596 * Get the gradient css for given gradient parameters.
1597 *
1598 * @param string $type The type of gradient. Default 'linear'.
1599 * @param string $color1 The first color of the gradient. Default '#FFC9B2'.
1600 * @param string $color2 The second color of the gradient. Default '#C7CBFF'.
1601 * @param int $loc1 The location of the first color. Default 0.
1602 * @param int $loc2 The location of the second color. Default 100.
1603 * @param int $angle The angle of the gradient. Default 90.
1604 *
1605 * @since 1.4.4
1606 * @return string The gradient css.
1607 */
1608 public static function get_gradient_css( $type = 'linear', $color1 = '#FFC9B2', $color2 = '#C7CBFF', $loc1 = 0, $loc2 = 100, $angle = 90 ) {
1609 if ( 'linear' === $type ) {
1610 return "linear-gradient({$angle}deg, {$color1} {$loc1}%, {$color2} {$loc2}%)";
1611 }
1612 return "radial-gradient({$color1} {$loc1}%, {$color2} {$loc2}%)";
1613 }
1614
1615 /**
1616 * Return the classes based on background and overlay type to add to the form container.
1617 *
1618 * @param string $background_type The background type.
1619 * @param string $overlay_type The overlay type.
1620 * @param string $bg_image The background image url.
1621 *
1622 * @since 1.4.4
1623 * @return string The classes to add to the form container.
1624 */
1625 public static function get_background_classes( $background_type, $overlay_type, $bg_image = '' ) {
1626 if ( empty( $background_type ) ) {
1627 $background_type = 'color';
1628 }
1629
1630 $background_type_class = '';
1631 $overlay_class = 'image' === $background_type && ! empty( $bg_image ) && $overlay_type ? "srfm-overlay-{$overlay_type}" : '';
1632
1633 // Set the class based on the background type.
1634 switch ( $background_type ) {
1635 case 'image':
1636 $background_type_class = 'srfm-bg-image';
1637 break;
1638 case 'gradient':
1639 $background_type_class = 'srfm-bg-gradient';
1640 break;
1641 default:
1642 $background_type_class = 'srfm-bg-color';
1643 break;
1644 }
1645
1646 return self::join_strings( [ $background_type_class, $overlay_class ] );
1647 }
1648
1649 /**
1650 * Custom escape function for the textarea with rich text support.
1651 *
1652 * @param string $content The content submitted by the user in the textarea block.
1653 * @since 1.7.1
1654 *
1655 * @return string Escaped content.
1656 */
1657 public static function esc_textarea( $content ) {
1658 $content = wpautop( self::sanitize_textarea( $content ) );
1659
1660 return trim( str_replace( [ "\r\n", "\r", "\n" ], '', $content ) );
1661 }
1662
1663 /**
1664 * Custom sanitization function for the textarea with rich text support.
1665 *
1666 * @param string $content The content submitted by the user in the textarea block.
1667 * @since 1.7.1
1668 *
1669 * @return string Sanitized content.
1670 */
1671 public static function sanitize_textarea( $content ) {
1672 $count = 1;
1673 $content = convert_invalid_entities( $content );
1674
1675 // Remove the 'script' and 'style' tags recursively from the content.
1676 while ( $count ) {
1677 $content = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', self::get_string_value( $content ), - 1, $count );
1678 }
1679
1680 // Disable the safe style attribute parsing for the textarea block.
1681 add_filter( 'safe_style_css', [ self::class, 'disable_style_attr_parsing' ], 10, 1 );
1682 $content = wp_kses_post( self::get_string_value( $content ) );
1683
1684 // Remove the filter after sanitization to avoid affecting other blocks.
1685 remove_filter( 'safe_style_css', [ self::class, 'disable_style_attr_parsing' ], 10 );
1686
1687 // Ensure all tags are balanced.
1688 return force_balance_tags( $content );
1689 }
1690
1691 /**
1692 * Disable parsing of style attributes for the textarea block.
1693 *
1694 * @param array<string> $allowed_styles The allowed styles.
1695 * @since 1.7.1
1696 *
1697 * @return array An empty array to disable style attribute parsing.
1698 */
1699 public static function disable_style_attr_parsing( $allowed_styles ) {
1700 unset( $allowed_styles );
1701 // Disable parsing of style attributes.
1702 return [];
1703 }
1704 /**
1705 * Strips JavaScript attributes from HTML content.
1706 *
1707 * @param string $html The HTML content to process.
1708 * @param bool $remove_link_target Optional. When true, removes target and strips noopener/noreferrer from rel on links. Default false.
1709 * @since 1.7.1
1710 * @since 2.5.2 Added $remove_link_target parameter.
1711 * @return string The cleaned HTML content without JavaScript attributes.
1712 */
1713 public static function strip_js_attributes( $html, $remove_link_target = false ) {
1714 $dom = new \DOMDocument();
1715
1716 // Suppress warnings due to malformed HTML.
1717 libxml_use_internal_errors( true );
1718 $loaded = $dom->loadHTML( '<?xml encoding="utf-8" ?>' . $html );
1719 libxml_clear_errors();
1720
1721 if ( ! $loaded ) {
1722 return $html; // Return original HTML if loading fails.
1723 }
1724
1725 $xpath = new \DOMXPath( $dom );
1726
1727 // 1. Remove all <script> tags.
1728 $script_nodes = $xpath->query( '//script' );
1729 if ( $script_nodes instanceof \DOMNodeList ) {
1730 foreach ( $script_nodes as $script ) {
1731 // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- This is a DOM element.
1732 $parent_node = $script->parentNode;
1733 if ( $parent_node instanceof \DOMNode ) {
1734 $parent_node->removeChild( $script );
1735 }
1736 }
1737 }
1738
1739 // 2. Remove all attributes that start with "on" (like onclick, onmouseover, etc.).
1740 $elements_with_on_attrs = $xpath->query( '//*[@*[starts-with(name(), "on")]]' );
1741 if ( $elements_with_on_attrs instanceof \DOMNodeList ) {
1742 foreach ( $elements_with_on_attrs as $element ) {
1743 if ( $element instanceof \DOMElement && $element->hasAttributes() ) {
1744 foreach ( iterator_to_array( $element->attributes ) as $attr ) {
1745 if ( $attr instanceof \DOMAttr && stripos( $attr->name, 'on' ) === 0 ) {
1746 $element->removeAttribute( $attr->name );
1747 }
1748 }
1749 }
1750 }
1751 }
1752
1753 // 3. Optionally remove target and target-related rel values (noopener, noreferrer) from links.
1754 if ( $remove_link_target ) {
1755 $links = $xpath->query( '//a[@target]' );
1756 if ( $links instanceof \DOMNodeList ) {
1757 foreach ( $links as $link ) {
1758 if ( $link instanceof \DOMElement ) {
1759 $link->removeAttribute( 'target' );
1760 $rel = $link->getAttribute( 'rel' );
1761 if ( $rel ) {
1762 $cleaned_rel = trim( (string) preg_replace( '/\s+/', ' ', (string) preg_replace( '/\b(noopener|noreferrer)\b/i', '', $rel ) ) );
1763 if ( $cleaned_rel ) {
1764 $link->setAttribute( 'rel', $cleaned_rel );
1765 } else {
1766 $link->removeAttribute( 'rel' );
1767 }
1768 }
1769 }
1770 }
1771 }
1772 }
1773
1774 // Return cleaned HTML.
1775 $body = $dom->getElementsByTagName( 'body' )->item( 0 );
1776 if ( $body instanceof \DOMNode ) {
1777 $cleaned_html = $dom->saveHTML( $body );
1778 return is_string( $cleaned_html ) ? $cleaned_html : '';
1779 }
1780 return '';
1781 }
1782
1783 /**
1784 * Encodes the given string with base64.
1785 * Moved from admin class to here.
1786 *
1787 * @param string $logo contains svg's.
1788 * @return string
1789 */
1790 public static function encode_svg( $logo ) {
1791 return 'data:image/svg+xml;base64,' . base64_encode( $logo ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
1792 }
1793
1794 /**
1795 * Get plugin status
1796 *
1797 * @since 0.0.1
1798 * @since 1.7.0 moved to inc/helper.php from inc/admin-ajax.php
1799 *
1800 * @param string $plugin_init_file Plugin init file.
1801 * @return string
1802 */
1803 public static function get_plugin_status( $plugin_init_file ) {
1804
1805 $installed_plugins = get_plugins();
1806
1807 if ( ! isset( $installed_plugins[ $plugin_init_file ] ) ) {
1808 return 'Install';
1809 }
1810 if ( is_plugin_active( $plugin_init_file ) ) {
1811 return 'Activated';
1812 }
1813 return 'Installed';
1814 }
1815
1816 /**
1817 * Return the first installed plugin from a list, or a default if none exist.
1818 *
1819 * @since 2.0.0
1820 *
1821 * @param array<string> $plugins_to_check Plugin file paths to check, in priority order.
1822 * @param string $default Optional fallback plugin file path. Default empty string.
1823 *
1824 * @return string First installed plugin file path, or the default.
1825 */
1826 public static function get_plugin_if_installed( $plugins_to_check, $default = '' ) {
1827 if ( ! function_exists( 'get_plugins' ) ) {
1828 require_once ABSPATH . 'wp-admin/includes/plugin.php';
1829 }
1830
1831 $plugins = get_plugins();
1832
1833 foreach ( self::get_array_value( $plugins_to_check ) as $plugin_file ) {
1834 if ( isset( $plugins[ $plugin_file ] ) ) {
1835 return $plugin_file;
1836 }
1837 }
1838
1839 return $default;
1840 }
1841
1842 /**
1843 * Check which Starter Templates plugin is installed and return its main plugin file path.
1844 *
1845 * @since 1.7.3
1846 *
1847 * @return string The main plugin file path of the installed Starter Templates plugin.
1848 */
1849 public static function check_starter_template_plugin() {
1850 return self::get_plugin_if_installed(
1851 [ 'astra-pro-sites/astra-pro-sites.php' ],
1852 'astra-sites/astra-sites.php'
1853 );
1854 }
1855
1856 /**
1857 * Get sureforms recommended integrations.
1858 *
1859 * @since 0.0.1
1860 * @since 1.7.0 moved to inc/helper.php from inc/admin-ajax.php
1861 *
1862 * @return array<mixed>
1863 */
1864 public static function sureforms_get_integration() {
1865 $suretrigger_connected = apply_filters( 'suretriggers_is_user_connected', '' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- SureTriggers' own filter; the name must match SureTriggers exactly to integrate.
1866 $logo_sure_triggers = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suretriggers.svg' );
1867 $logo_full = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suretriggers_full.svg' );
1868 $logo_sure_mails = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suremails.svg' );
1869 $logo_uae = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/uae.svg' );
1870 $logo_starter_templates = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/starterTemplates.svg' );
1871 $logo_sure_rank = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/surerank.svg' );
1872 $logo_sure_contact = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/surecontact.svg' );
1873 $logo_sure_donation = file_get_contents( plugin_dir_path( SRFM_FILE ) . 'images/suredonation.svg' );
1874
1875 $integrations = [
1876 'sure_donation' => [
1877 'title' => __( 'SureDonation', 'sureforms' ),
1878 'singleLineDescription' => __( 'Start Collecting Donations Today', 'sureforms' ),
1879 'subtitle' => __( 'Want to accept donations too? SureDonation makes it easy to collect contributions right on your WordPress site.', 'sureforms' ),
1880 'status' => self::get_plugin_status( 'suredonation/suredonation.php' ),
1881 'slug' => 'suredonation',
1882 'path' => 'suredonation/suredonation.php',
1883 'logo' => self::encode_svg( is_string( $logo_sure_donation ) ? $logo_sure_donation : '' ),
1884 ],
1885 'sure_contact' => [
1886 'title' => __( 'SureContact', 'sureforms' ),
1887 'singleLineDescription' => __( 'Turn Emails Into Revenue with a CRM Built for Your Website!', 'sureforms' ),
1888 'subtitle' => __( 'Send newsletters, run campaigns, set up automations, manage contacts, and see exactly how much revenue your emails generate, all in one place.', 'sureforms' ),
1889 'status' => self::get_plugin_status( 'surecontact/surecontact.php' ),
1890 'slug' => 'surecontact',
1891 'path' => 'surecontact/surecontact.php',
1892 'logo' => self::encode_svg( is_string( $logo_sure_contact ) ? $logo_sure_contact : '' ),
1893 ],
1894 'sure_mails' => [
1895 'title' => __( 'SureMail', 'sureforms' ),
1896 'singleLineDescription' => __( 'Boost Your Email Deliverability Instantly!', 'sureforms' ),
1897 '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' ),
1898 'status' => self::get_plugin_status( 'suremails/suremails.php' ),
1899 'slug' => 'suremails',
1900 'path' => 'suremails/suremails.php',
1901 'logo' => self::encode_svg( is_string( $logo_sure_mails ) ? $logo_sure_mails : '' ),
1902 ],
1903 'sure_triggers' => [
1904 'title' => __( 'OttoKit', 'sureforms' ),
1905 'singleLineDescription' => __( 'Automate your WordPress workflows effortlessly.', 'sureforms' ),
1906 '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' ),
1907 'status' => self::get_plugin_status( 'suretriggers/suretriggers.php' ),
1908 'slug' => 'suretriggers',
1909 'path' => 'suretriggers/suretriggers.php',
1910 'logo' => self::encode_svg( is_string( $logo_sure_triggers ) ? $logo_sure_triggers : '' ),
1911 'logo_full' => self::encode_svg( is_string( $logo_full ) ? $logo_full : '' ),
1912 'connected' => $suretrigger_connected,
1913 'connection_url' => admin_url( 'admin.php?page=suretriggers' ),
1914 ],
1915 'starter_templates' => [
1916 'title' => __( 'Starter Templates', 'sureforms' ),
1917 'singleLineDescription' => __( 'Launch Beautiful Websites in Minutes!', 'sureforms' ),
1918 'subtitle' => __( 'Choose from professionally designed templates, import with one click, and customize effortlessly to match your brand.', 'sureforms' ),
1919 'status' => self::get_plugin_status( self::check_starter_template_plugin() ),
1920 'slug' => 'astra-sites',
1921 'path' => self::check_starter_template_plugin(),
1922 'logo' => self::encode_svg( is_string( $logo_starter_templates ) ? $logo_starter_templates : '' ),
1923 ],
1924 ];
1925
1926 $elementor_installed = self::get_plugin_if_installed( [ 'elementor/elementor.php' ] );
1927
1928 if ( $elementor_installed ) {
1929 $integrations['uae'] = [
1930 'title' => __( 'Ultimate Addons for Elementor', 'sureforms' ),
1931 'singleLineDescription' => __( 'Power Up Elementor to Build Stunning Websites Faster!', 'sureforms' ),
1932 'subtitle' => __( 'Enhance Elementor with powerful widgets and templates. Build stunning, high-performing websites faster with creative design elements and seamless customization.', 'sureforms' ),
1933 'status' => self::get_plugin_status( 'header-footer-elementor/header-footer-elementor.php' ),
1934 'slug' => 'header-footer-elementor',
1935 'path' => 'header-footer-elementor/header-footer-elementor.php',
1936 'logo' => self::encode_svg( is_string( $logo_uae ) ? $logo_uae : '' ),
1937 ];
1938 } else {
1939 $integrations['sure_rank'] = [
1940 'title' => __( 'SureRank', 'sureforms' ),
1941 'singleLineDescription' => __( 'Elevate Your SEO and Climb Search Rankings Effortlessly!', 'sureforms' ),
1942 'subtitle' => __( 'Boost your website\'s visibility with smart SEO automation. Optimize content, track keyword performance, and get actionable insights, all inside WordPress.', 'sureforms' ),
1943 'status' => self::get_plugin_status( 'surerank/surerank.php' ),
1944 'slug' => 'surerank',
1945 'path' => 'surerank/surerank.php',
1946 'logo' => self::encode_svg( is_string( $logo_sure_rank ) ? $logo_sure_rank : '' ),
1947 ];
1948 }
1949
1950 return apply_filters( 'srfm_integrated_plugins', $integrations );
1951 }
1952
1953 /**
1954 * Get the current rotating plugin for the banner.
1955 *
1956 * Plugins rotate every 2 days. Only non-activated plugins are shown.
1957 * Returns false if all plugins are activated.
1958 *
1959 * @since 2.0.0
1960 * @return array<string, mixed>|false The current plugin data or false if all plugins are activated.
1961 */
1962 public static function get_rotating_plugin_banner() {
1963 $all_plugins = self::sureforms_get_integration();
1964
1965 if ( ! is_array( $all_plugins ) ) {
1966 return false;
1967 }
1968
1969 $available_plugins = [];
1970
1971 // Only include non-activated plugins.
1972 foreach ( $all_plugins as $plugin ) {
1973 if ( ! is_array( $plugin ) ) {
1974 continue;
1975 }
1976 if ( isset( $plugin['status'] ) && is_string( $plugin['status'] ) && 'Activated' !== $plugin['status'] ) {
1977 $available_plugins[] = $plugin;
1978 }
1979 }
1980
1981 // Re-index the array to have sequential numeric keys.
1982 $available_plugins = array_values( $available_plugins );
1983 $total_plugins = count( $available_plugins );
1984
1985 // Hide section if all plugins are active.
1986 if ( 0 === $total_plugins ) {
1987 return false;
1988 }
1989
1990 // Get stored rotation data.
1991 $rotation_data = self::get_srfm_option( 'plugin_banner_rotation', [] );
1992
1993 if ( ! is_array( $rotation_data ) ) {
1994 $rotation_data = [];
1995 }
1996
1997 // Initialize rotation data if empty.
1998 if ( empty( $rotation_data ) ) {
1999 $current_time = time();
2000 self::update_srfm_option(
2001 'plugin_banner_rotation',
2002 [
2003 'last_rotation_date' => $current_time,
2004 'plugin_index' => 0,
2005 ]
2006 );
2007 return isset( $available_plugins[0] ) && is_array( $available_plugins[0] ) ? $available_plugins[0] : false;
2008 }
2009
2010 $last_rotation_date = isset( $rotation_data['last_rotation_date'] ) && is_int( $rotation_data['last_rotation_date'] ) ? $rotation_data['last_rotation_date'] : 0;
2011 $plugin_index = isset( $rotation_data['plugin_index'] ) && is_numeric( $rotation_data['plugin_index'] ) ? intval( $rotation_data['plugin_index'] ) : 0;
2012
2013 $current_time = time();
2014 $days_since_rotation = ( $current_time - $last_rotation_date ) / DAY_IN_SECONDS;
2015
2016 // Rotate every 2 days.
2017 if ( $days_since_rotation >= 2 ) {
2018 // Rotate to next plugin.
2019 ++$plugin_index;
2020 $plugin_index %= $total_plugins;
2021
2022 // Update the rotation data.
2023 self::update_srfm_option(
2024 'plugin_banner_rotation',
2025 [
2026 'last_rotation_date' => $current_time,
2027 'plugin_index' => $plugin_index,
2028 ]
2029 );
2030 }
2031
2032 // Ensure the index is within bounds.
2033 if ( $plugin_index >= $total_plugins ) {
2034 $plugin_index = 0;
2035 }
2036
2037 return isset( $available_plugins[ $plugin_index ] ) && is_array( $available_plugins[ $plugin_index ] ) ? $available_plugins[ $plugin_index ] : false;
2038 }
2039
2040 /**
2041 * Get a value from the srfm_options array.
2042 *
2043 * @param string $key The key to retrieve.
2044 * @param mixed $default The default value to return if the key does not exist.
2045 * @since 1.8.0
2046 * @return mixed
2047 */
2048 public static function get_srfm_option( $key, $default = null ) {
2049 $options = get_option( 'srfm_options', [] );
2050 if ( ! is_array( $options ) ) {
2051 $options = [];
2052 }
2053 return array_key_exists( $key, $options ) ? $options[ $key ] : $default;
2054 }
2055
2056 /**
2057 * Update a value in the srfm_options array.
2058 *
2059 * @param string $key The key to update.
2060 * @param mixed $value The value to set.
2061 * @since 1.8.0
2062 * @return void
2063 */
2064 public static function update_srfm_option( $key, $value ) {
2065 $options = get_option( 'srfm_options', [] );
2066 if ( ! is_array( $options ) ) {
2067 $options = [];
2068 }
2069 $options[ $key ] = $value;
2070 update_option( 'srfm_options', $options );
2071 }
2072
2073 /**
2074 * Get the WordPress file types.
2075 *
2076 * @since 1.7.4
2077 * @return array<string,mixed> An associative array representing the file types.
2078 */
2079 public static function get_wp_file_types() {
2080 $formats = [];
2081 $mimes = get_allowed_mime_types();
2082 $maxsize = wp_max_upload_size() / 1048576;
2083 if ( ! empty( $mimes ) ) {
2084 foreach ( $mimes as $type => $mime ) {
2085 $multiple = explode( '|', $type );
2086 foreach ( $multiple as $single ) {
2087 $formats[] = $single;
2088 }
2089 }
2090 }
2091
2092 return [
2093 'formats' => $formats,
2094 'maxsize' => $maxsize,
2095 ];
2096 }
2097
2098 /**
2099 * Determines if the SureForms Pro plugin is installed and active.
2100 *
2101 * Checks for the presence of the SRFM_PRO_VER constant.
2102 *
2103 * @since 1.8.0
2104 *
2105 * @return bool True if the Pro plugin is active; false otherwise.
2106 */
2107 public static function has_pro() {
2108 return defined( 'SRFM_PRO_VER' );
2109 }
2110
2111 /**
2112 * Verifies the request by checking the nonce and user capabilities.
2113 *
2114 * @param string $request_type The type of request, either 'rest' or 'ajax'.
2115 * @param string $nonce_action The action name for the nonce.
2116 * @param string $nonce_name The name of the nonce field.
2117 * @param string $capability The capability required to perform the action. Default is 'manage_options'.
2118 *
2119 * @since 1.10.0
2120 * @return void
2121 */
2122 public static function verify_nonce_and_capabilities( $request_type, $nonce_action, $nonce_name, $capability = 'manage_options' ) {
2123
2124 if ( ! is_string( $nonce_action ) || ! is_string( $nonce_name ) || empty( $nonce_action ) || empty( $nonce_name ) ) {
2125 wp_send_json_error(
2126 [ 'message' => __( 'Invalid nonce action or name.', 'sureforms' ) ],
2127 400
2128 );
2129 }
2130
2131 // Verify nonce for security.
2132 if ( 'rest' === $request_type ) {
2133 // For REST API requests, use the WP_REST_Request object to verify the nonce.
2134 if ( ! wp_verify_nonce( $nonce_action, $nonce_name ) ) {
2135 wp_send_json_error(
2136 [ 'message' => __( 'Invalid security token.', 'sureforms' ) ],
2137 403
2138 );
2139 }
2140 } elseif ( 'ajax' === $request_type ) {
2141 // For non-REST requests, use the standard nonce verification.
2142 if ( ! check_ajax_referer( $nonce_action, $nonce_name, false ) ) {
2143 wp_send_json_error(
2144 [ 'message' => __( 'Invalid security token.', 'sureforms' ) ],
2145 403
2146 );
2147 }
2148 } else {
2149 // If the request type is not recognized, return an error.
2150 wp_send_json_error(
2151 [ 'message' => __( 'Invalid request type.', 'sureforms' ) ],
2152 400
2153 );
2154 }
2155
2156 // Check user capabilities.
2157 if ( ! current_user_can( $capability ) ) {
2158 wp_send_json_error(
2159 [ 'message' => esc_html__( 'You do not have permission to perform this action.', 'sureforms' ) ],
2160 403
2161 );
2162 }
2163 }
2164
2165 /**
2166 * Get the block name from a field name by extracting the first two parts.
2167 *
2168 * @param string $field_name The full field name (e.g., 'srfm-text-lbl-123').
2169 *
2170 * @since 1.11.0
2171 * @return string The block name (e.g., 'srfm-text').
2172 */
2173 public static function get_block_name_from_field( $field_name ) {
2174 return implode( '-', array_slice( explode( '-', explode( '-lbl-', $field_name )[0] ), 0, 2 ) );
2175 }
2176
2177 /**
2178 * Check if any of the top 10 popular WordPress SMTP plugins is active using array_intersect.
2179 *
2180 * @since 1.9.1
2181 * @return bool True if any SMTP plugin is active, false otherwise.
2182 */
2183 public static function is_any_smtp_plugin_active() {
2184 $smtp_plugins = [
2185 'wp-mail-smtp/wp_mail_smtp.php',
2186 'post-smtp/postman-smtp.php',
2187 'easy-wp-smtp/easy-wp-smtp.php',
2188 'wp-smtp/wp-smtp.php',
2189 'newsletter/plugin.php',
2190 'fluent-smtp/fluent-smtp.php',
2191 'pepipost-smtp/pepipost-smtp.php',
2192 'mail-bank/wp-mail-bank.php',
2193 'smtp-mailer/smtp-mailer.php',
2194 'suremails/suremails.php',
2195 'site-mailer/site-mailer.php',
2196 ];
2197
2198 $active_plugins = (array) get_option( 'active_plugins', [] );
2199 // For multisite, merge sitewide active plugins.
2200 if ( is_multisite() ) {
2201 $network_plugins = (array) get_site_option( 'active_sitewide_plugins', [] );
2202 $active_plugins = array_merge( $active_plugins, array_keys( $network_plugins ) );
2203 }
2204
2205 return (bool) array_intersect( $smtp_plugins, $active_plugins );
2206 }
2207
2208 /**
2209 * Apply a filter and return the filtered value only if it's a non-empty array.
2210 * Otherwise, return the default array.
2211 *
2212 * @param string $filter_name The name of the filter to apply.
2213 * @param mixed $default The default array to return if the filtered result is invalid.
2214 * @param mixed ...$args Additional arguments to pass to the filter.
2215 *
2216 * @return array The filtered array if valid, otherwise the default.
2217 */
2218 public static function apply_filters_as_array( $filter_name, $default, ...$args ) {
2219 // Ensure $default is an array.
2220 if ( ! is_array( $default ) ) {
2221 $default = [];
2222 }
2223
2224 // Validate the filter name.
2225 if ( ! is_string( $filter_name ) || empty( $filter_name ) ) {
2226 return $default;
2227 }
2228
2229 // Apply the filter with additional arguments.
2230 $filtered = apply_filters( $filter_name, $default, ...$args ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- Generic dynamic-filter dispatcher; the caller supplies the (already prefixed) hook name.
2231
2232 // Return filtered result if it's a non-empty array.
2233 return is_array( $filtered ) && ! empty( $filtered ) ? $filtered : $default;
2234 }
2235
2236 /**
2237 * Get forms with entry counts for a specific time period.
2238 *
2239 * @param int $timestamp The timestamp to get entries after.
2240 * @param int $limit Maximum number of forms to return (0 for all).
2241 * @param bool $sort Whether to sort by entry count descending.
2242 * @return array Array of form data with entry counts.
2243 * @since 1.9.1
2244 */
2245 public static function get_forms_with_entry_counts( $timestamp, $limit = 0, $sort = true ) {
2246 // Get all published forms with post objects for bulk title access.
2247 $args = [
2248 'post_type' => SRFM_FORMS_POST_TYPE,
2249 'posts_per_page' => -1,
2250 'post_status' => 'publish',
2251 'orderby' => 'ID',
2252 'order' => 'DESC',
2253 'no_found_rows' => true,
2254 'update_post_term_cache' => false,
2255 'update_post_meta_cache' => false,
2256 ];
2257
2258 $query = new \WP_Query( $args );
2259
2260 if ( ! $query->have_posts() ) {
2261 return [];
2262 }
2263
2264 $all_forms = [];
2265
2266 // Process posts directly from the query results without touching global $post.
2267 foreach ( $query->posts as $form ) {
2268 // Ensure we have a valid post object.
2269 if ( ! $form instanceof \WP_Post ) {
2270 continue;
2271 }
2272
2273 $form_id = (int) $form->ID;
2274 if ( $form_id <= 0 ) {
2275 continue;
2276 }
2277
2278 // Get entries count after the timestamp for this specific form.
2279 $entry_count = Entries::get_entries_count_after( $timestamp, $form_id );
2280
2281 // Get form title directly from post object, use "Blank Form" if empty.
2282 $form_title = $form->post_title;
2283 if ( empty( trim( self::get_string_value( $form_title ) ) ) ) {
2284 $form_title = __( 'Blank Form', 'sureforms' );
2285 }
2286
2287 $all_forms[] = [
2288 'form_id' => $form_id,
2289 'title' => $form_title,
2290 'count' => $entry_count,
2291 ];
2292 }
2293
2294 // Sort by count descending, then by form_id descending for consistency.
2295 if ( $sort ) {
2296 usort(
2297 $all_forms,
2298 static function( $a, $b ) {
2299 if ( $a['count'] === $b['count'] ) {
2300 return $b['form_id'] - $a['form_id'];
2301 }
2302 return $b['count'] - $a['count'];
2303 }
2304 );
2305 }
2306
2307 // Return limited results if specified.
2308 if ( $limit > 0 ) {
2309 return array_slice( $all_forms, 0, $limit );
2310 }
2311
2312 return $all_forms;
2313 }
2314
2315 /**
2316 * Check if the given form ID is valid SureForms form ID.
2317 * A valid form ID is a numeric value that corresponds to an existing SureForms form in the database.
2318 *
2319 * @since 1.9.1
2320 *
2321 * @param int|string|mixed $form_id The form ID to validate.
2322 * @return bool True if the form ID is valid, false otherwise.
2323 */
2324 public static function is_valid_form( $form_id ) {
2325
2326 // Check for a valid form ID.
2327 if ( empty( $form_id ) || ! is_numeric( $form_id ) ) {
2328 return false;
2329 }
2330
2331 // Check if the form ID exists in the database.
2332 $form = get_post( self::get_integer_value( $form_id ) );
2333
2334 // If the form does not exist or is not of the correct post type, return false.
2335 if ( ! $form || ! is_a( $form, 'WP_Post' ) || SRFM_FORMS_POST_TYPE !== $form->post_type ) {
2336 return false;
2337 }
2338
2339 return true;
2340 }
2341
2342 /**
2343 * Get the timestamp from a string.
2344 *
2345 * This function uses WordPress's configured timezone (from Settings → General → Timezone)
2346 * to ensure consistent behavior regardless of the server's timezone settings.
2347 *
2348 * @param string $date The date in YYYY-MM-DD format (e.g., '2026-01-10').
2349 * @param string $hours The hours in 12-hour format (e.g., '12', '01'-'12').
2350 * @param string $minutes The minutes (e.g., '00', '00'-'59').
2351 * @param string $meridiem The meridiem (e.g., 'AM' or 'PM').
2352 *
2353 * @since 1.10.1
2354 * @return int|false The timestamp if successful, false otherwise.
2355 */
2356 public static function get_timestamp_from_string( $date, $hours = '12', $minutes = '00', $meridiem = 'AM' ) {
2357
2358 if ( empty( $date ) || ! is_string( $date ) ) {
2359 return false; // Invalid input.
2360 }
2361
2362 // Ensure the date is in a valid format of YYYY-MM-DD.
2363 if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $date ) ) {
2364 return false; // Invalid date format.
2365 }
2366
2367 $time_string = $date . ' ' . $hours . ':' . $minutes . ' ' . $meridiem;
2368
2369 // Convert to timestamp using WordPress timezone.
2370 // This ensures the date/time is interpreted in the site's configured timezone,
2371 // not the server's timezone or PHP's default timezone.
2372 try {
2373 $datetime = date_create( $time_string, wp_timezone() );
2374
2375 if ( false === $datetime ) {
2376 return false;
2377 }
2378
2379 $timestamp = $datetime->getTimestamp();
2380
2381 if ( is_int( $timestamp ) && $timestamp > 0 ) {
2382 return $timestamp;
2383 }
2384 } catch ( \Exception $e ) {
2385 // If timezone conversion fails, return false.
2386 return false;
2387 }
2388
2389 // If conversion fails, return false.
2390 return false;
2391 }
2392
2393 /**
2394 * Generate a unique ID for the saved form.
2395 * Also ensures that the generated ID does not already exist in the database table.
2396 *
2397 * @param class-string $class The class name where the get method is defined to check for existing IDs.
2398 * @param int<1, max> $length The length of the random bytes to generate. Default is 8.
2399 * @return string
2400 * @since 2.2.0
2401 */
2402 public static function generate_unique_id( $class, $length = 8 ) {
2403 // Ensure length is at least 1.
2404 $length = max( 1, $length );
2405
2406 do {
2407 $id = bin2hex( random_bytes( $length ) );
2408 } while ( is_callable( [ $class, 'get' ] ) && call_user_func( [ $class, 'get' ], $id ) );
2409 return $id;
2410 }
2411
2412 /**
2413 * Log error messages to the error log.
2414 *
2415 * This function checks if error_log function exists, validates the message,
2416 * and logs it with the print_r second argument set to true.
2417 *
2418 * Logging is disabled by default. To enable logging, add this to wp-config.php:
2419 * define( 'SRFM_LOG', true );
2420 *
2421 * @param mixed $message The error message to log. Can be string or any type.
2422 * @param string $prefix Optional prefix to add before the message. Default: 'Log :'.
2423 *
2424 * @since 2.0.0
2425 * @return void
2426 */
2427 public static function srfm_log( $message, $prefix = 'Log :' ) {
2428 // Check if logging is enabled via SRFM_LOG constant.
2429 if ( ! defined( 'SRFM_LOG' ) ) {
2430 return;
2431 }
2432 unset( $message, $prefix );
2433 }
2434
2435 /**
2436 * Encodes data to base64 after JSON encoding with validation.
2437 *
2438 * This function checks if the data is non-empty and valid for JSON encoding.
2439 * If data is not valid, returns an empty string.
2440 * Otherwise, it attempts to JSON encode and then base64 encode the result.
2441 *
2442 * @param mixed $data The data to JSON encode and then base64 encode.
2443 * @return string The base64-encoded JSON string, or empty string on failure.
2444 */
2445 public static function srfm_base64_json_encode( $data ) {
2446 if ( empty( $data ) || ! is_array( $data ) ) {
2447 return '';
2448 }
2449
2450 $json = wp_json_encode( $data );
2451 if ( false === $json || '' === $json ) {
2452 return '';
2453 }
2454
2455 // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
2456 return base64_encode( $json );
2457 }
2458
2459 /**
2460 * Get the visitor's IP address.
2461 *
2462 * Centralised IP detection that checks common proxy headers before
2463 * falling back to REMOTE_ADDR. Handles comma-separated IPs that
2464 * load-balancers / CDNs may append (takes the first, i.e. client IP).
2465 *
2466 * NOTE: Existing callers (Smart_Tags::get_the_user_ip, Front_End::get_user_ip,
2467 * inline reads in Form_Submit) can be migrated to this method in the future
2468 * to avoid duplicating the same header-chain logic.
2469 *
2470 * @since 2.8.0
2471 * @return string Validated IP address, or empty string if unavailable.
2472 */
2473 public static function get_visitor_ip() {
2474 $headers = [
2475 'HTTP_CLIENT_IP',
2476 'HTTP_X_FORWARDED_FOR',
2477 'HTTP_X_REAL_IP',
2478 'HTTP_X_FORWARDED',
2479 'HTTP_FORWARDED_FOR',
2480 'HTTP_FORWARDED',
2481 'REMOTE_ADDR',
2482 ];
2483
2484 foreach ( $headers as $header ) {
2485 if ( empty( $_SERVER[ $header ] ) ) {
2486 continue;
2487 }
2488
2489 // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Validated by FILTER_VALIDATE_IP below.
2490 $raw = wp_unslash( $_SERVER[ $header ] );
2491
2492 // Proxies may send comma-separated IPs; the first is the original client.
2493 if ( false !== strpos( $raw, ',' ) ) {
2494 $raw = trim( explode( ',', $raw )[0] );
2495 }
2496
2497 $ip = filter_var( $raw, FILTER_VALIDATE_IP );
2498 if ( false !== $ip ) {
2499 /**
2500 * Filters the detected visitor IP address.
2501 *
2502 * @since 2.8.0
2503 *
2504 * @param string $ip Validated IP address.
2505 */
2506 return apply_filters( 'srfm_visitor_ip', $ip );
2507 }
2508 }
2509
2510 return '';
2511 }
2512
2513 /**
2514 * Detect the visitor's 2-letter country code via server-side IP geolocation.
2515 *
2516 * Prefers a CDN/server-provided country header (Cloudflare, CloudFront, mod_geoip)
2517 * when present — free, instant and cache-safe. Otherwise calls ipapi.co once per
2518 * visitor IP and caches the result in a transient for 24 hours so subsequent
2519 * lookups for the same IP resolve instantly. Failures are cached for a short TTL
2520 * (see get_geo_failure_ttl()) to avoid retry storms while still self-healing, and
2521 * a site-wide hourly cap (filterable via `srfm_geo_api_hourly_cap`, default 40)
2522 * bounds outbound calls. Private/reserved IPs are rejected up front.
2523 *
2524 * Intended to be called per-visitor (e.g. via the geo-country REST route) so
2525 * the result is correct on full-page-cached sites instead of being baked into
2526 * the cached HTML.
2527 *
2528 * Local testing: private/loopback IPs (e.g. 127.0.0.1) cannot be geolocated, so
2529 * inject a public IP via the `srfm_visitor_ip` filter to exercise detection:
2530 *
2531 * add_filter( 'srfm_visitor_ip', static fn() => '8.8.8.8' ); // US; try 1.1.1.1 etc.
2532 *
2533 * @param string $fallback Country code returned when detection is unavailable.
2534 * @since 2.11.1
2535 * @return string Lowercase 2-letter country code.
2536 */
2537 public static function get_geo_country( $fallback = 'us' ) {
2538 // Prefer a CDN/server-provided country header — free, instant, per-visitor
2539 // and cache-safe. It is independent of the connecting IP (it still resolves
2540 // when the visitor IP is private/loopback, e.g. local dev or behind a
2541 // proxy), so it must be checked before the IP-based path below.
2542 $cdn_country = self::get_cdn_country();
2543 if ( '' !== $cdn_country ) {
2544 return $cdn_country;
2545 }
2546
2547 $ip = self::get_visitor_ip();
2548 if ( empty( $ip ) ) {
2549 return $fallback;
2550 }
2551
2552 // Reject private/reserved IPs: ipapi.co cannot geolocate them, and accepting
2553 // them would let spoofed X-Forwarded-For headers flood the transient cache.
2554 if ( ! filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE ) ) {
2555 return $fallback;
2556 }
2557
2558 // Versioned key (v2) so stale failure transients written by older code
2559 // (which used the byte-identical 'srfm_geo_' key and a 1h TTL) don't shadow
2560 // the current CDN/fallback logic for the failure-TTL window after an upgrade.
2561 $cache_key = 'srfm_geo_v2_' . md5( $ip );
2562 $cached = get_transient( $cache_key );
2563 if ( is_string( $cached ) && '' !== $cached ) {
2564 return $cached;
2565 }
2566
2567 // Site-wide hourly cap on outbound ipapi calls; the counter rolls over
2568 // every hour (key includes YmdH) so it never needs an explicit reset.
2569 $quota_key = 'srfm_geo_quota_' . gmdate( 'YmdH' );
2570 $quota_cap = self::get_integer_value( apply_filters( 'srfm_geo_api_hourly_cap', 40 ) );
2571 $count = self::get_integer_value( get_transient( $quota_key ) );
2572 if ( $count >= $quota_cap ) {
2573 self::srfm_log( $quota_cap, 'SRFM geo lookup skipped (hourly cap reached):' );
2574 // Do NOT cache a per-IP transient here: the hourly counter already
2575 // blocks outbound calls, and writing per IP is the one path not bounded
2576 // by the cap — it would let spoofed X-Forwarded-For headers churn
2577 // wp_options / the object cache under sustained traffic.
2578 return $fallback;
2579 }
2580 set_transient( $quota_key, $count + 1, HOUR_IN_SECONDS );
2581
2582 // Pass the visitor's IP explicitly via /{ip}/json/ — the request originates
2583 // from the server, so the bare /json/ endpoint would return the host's country.
2584 $url = 'https://ipapi.co/' . rawurlencode( $ip ) . '/json/';
2585
2586 // ipapi.co's free (keyless) tier is heavily rate-limited, so unauthenticated
2587 // lookups are best-effort and often fail to the configured fallback. Sites
2588 // that need reliable IP-based detection can supply a paid ipapi.co key via
2589 // this filter; CDN-fronted sites resolve earlier via get_cdn_country() and
2590 // never reach this call.
2591 $api_key = self::get_string_value( apply_filters( 'srfm_ipapi_api_key', '' ) );
2592 if ( '' !== $api_key ) {
2593 $url = add_query_arg( 'key', rawurlencode( $api_key ), $url );
2594 }
2595
2596 $response = wp_remote_get(
2597 $url,
2598 [
2599 'timeout' => 3,
2600 'user-agent' => 'SureForms/' . SRFM_VER . ' (+https://sureforms.com)',
2601 ]
2602 );
2603
2604 if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
2605 $detail = is_wp_error( $response ) ? $response->get_error_message() : wp_remote_retrieve_response_code( $response );
2606 self::srfm_log( $detail, 'SRFM geo lookup failed (transport):' );
2607 set_transient( $cache_key, $fallback, self::get_geo_failure_ttl() );
2608 return $fallback;
2609 }
2610
2611 $body = json_decode( wp_remote_retrieve_body( $response ), true );
2612
2613 // ipapi.co's free tier returns HTTP 200 with a JSON error body
2614 // (e.g. {"error":true,"reason":"RateLimited"}) when throttled — treat as a failure.
2615 if ( is_array( $body ) && ! empty( $body['error'] ) ) {
2616 $reason = ! empty( $body['reason'] ) && is_string( $body['reason'] ) ? $body['reason'] : 'unknown';
2617 self::srfm_log( $reason, 'SRFM geo lookup failed (ipapi error):' );
2618 set_transient( $cache_key, $fallback, self::get_geo_failure_ttl() );
2619 return $fallback;
2620 }
2621
2622 if ( ! is_array( $body ) || empty( $body['country_code'] ) || ! is_string( $body['country_code'] ) ) {
2623 self::srfm_log( wp_remote_retrieve_response_code( $response ), 'SRFM geo lookup failed (no country_code):' );
2624 set_transient( $cache_key, $fallback, self::get_geo_failure_ttl() );
2625 return $fallback;
2626 }
2627
2628 $country = strtolower( $body['country_code'] );
2629
2630 // Validate the external API response is a valid 2-letter country code.
2631 if ( ! preg_match( '/^[a-z]{2}$/', $country ) ) {
2632 self::srfm_log( $country, 'SRFM geo lookup failed (invalid country code):' );
2633 set_transient( $cache_key, $fallback, self::get_geo_failure_ttl() );
2634 return $fallback;
2635 }
2636
2637 set_transient( $cache_key, $country, DAY_IN_SECONDS );
2638
2639 return $country;
2640 }
2641
2642 /**
2643 * Read a visitor country code from a CDN / server geo header, if present.
2644 *
2645 * Many hosts sit behind Cloudflare, CloudFront or a geo-aware web server that
2646 * injects the visitor's country as a request header. This is free, instant,
2647 * per-visitor and works on full-page-cached sites, so we prefer it over an
2648 * outbound API call. Returns '' when no usable header is present.
2649 *
2650 * NOTE: these headers are client-spoofable when the site is NOT actually behind
2651 * the named CDN/proxy. The value is used only as a phone-field UI default (the
2652 * pre-selected flag), never for access control, so spoofing has no security
2653 * impact here — at worst a visitor sees a different default country.
2654 *
2655 * @since 2.11.1
2656 * @return string Lowercase 2-letter country code, or '' when unavailable.
2657 */
2658 private static function get_cdn_country() {
2659 $headers = [
2660 'HTTP_CF_IPCOUNTRY', // Cloudflare.
2661 'HTTP_CLOUDFRONT_VIEWER_COUNTRY', // AWS CloudFront.
2662 'GEOIP_COUNTRY_CODE', // Apache/Nginx mod_geoip / MaxMind.
2663 'HTTP_X_GEO_COUNTRY', // Some CDNs / reverse proxies.
2664 'HTTP_X_COUNTRY_CODE', // Some CDNs.
2665 ];
2666
2667 foreach ( $headers as $header ) {
2668 if ( empty( $_SERVER[ $header ] ) ) {
2669 continue;
2670 }
2671
2672 // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Validated by the regex below.
2673 $code = strtolower( trim( sanitize_text_field( wp_unslash( $_SERVER[ $header ] ) ) ) );
2674
2675 // Cloudflare sends 'xx' for unknown and 't1' for Tor; reject non-ISO values.
2676 if ( preg_match( '/^[a-z]{2}$/', $code ) && 'xx' !== $code && 't1' !== $code ) {
2677 return $code;
2678 }
2679 }
2680
2681 /**
2682 * Filters the CDN-derived visitor country code, before the ipapi.co fallback.
2683 *
2684 * Lets sites short-circuit detection with a server-side country code (e.g.
2685 * from a custom header) without any outbound API call.
2686 *
2687 * @since 2.11.1
2688 *
2689 * @param string $code Lowercase 2-letter country code, or '' if none found.
2690 */
2691 return apply_filters( 'srfm_cdn_country', '' );
2692 }
2693
2694 /**
2695 * TTL (in seconds) for caching a failed geo lookup.
2696 *
2697 * Short by default so a transient blip (rate-limit, timeout) self-heals on the
2698 * next visit instead of pinning the fallback country for a full hour, while
2699 * still preventing per-request retry storms. Filterable via `srfm_geo_failure_ttl`.
2700 *
2701 * @since 2.11.1
2702 * @return int
2703 */
2704 private static function get_geo_failure_ttl() {
2705 return self::get_integer_value( apply_filters( 'srfm_geo_failure_ttl', 5 * MINUTE_IN_SECONDS ) );
2706 }
2707
2708 }
2709