-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathfunctions.php
More file actions
544 lines (490 loc) · 15.2 KB
/
functions.php
File metadata and controls
544 lines (490 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Some utility function used alongside the plugin
*
* @link codekraft.it
* @since 0.0.1
*
* @package CF7_AntiSpam
* @subpackage CF7_AntiSpam/includes
*/
/**
* If the user is behind a proxy, get the IP address from the HTTP_CF_CONNECTING_IP header, otherwise get the IP address
* from the REMOTE_ADDR header
*
* @return mixed|string - The real ip address.
*/
function cf7a_get_real_ip() {
// Cloudflare: Most reliable when behind Cloudflare CDN.
// phpcs:ignore WordPressVIPMinimum.Variables.ServerVariables.UserControlledHeaders
$http_cf_connecting_ip = ! empty( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ? filter_var( wp_unslash( $_SERVER['HTTP_CF_CONNECTING_IP'] ), FILTER_VALIDATE_IP ) : false;
if ( ! empty( $http_cf_connecting_ip ) ) {
return $http_cf_connecting_ip;
}
// X-Forwarded-For: Standard proxy header, first IP is the client.
// phpcs:ignore WordPressVIPMinimum.Variables.ServerVariables.UserControlledHeaders, WordPressVIPMinimum.Variables.RestrictedVariables.cache_constraints___HTTP_X_FORWARDED_FOR__
$http_x_forwarded_for = ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) : false;
if ( ! empty( $http_x_forwarded_for ) ) {
return filter_var( trim( current( explode( ',', $http_x_forwarded_for ) ) ), FILTER_VALIDATE_IP );
}
// REMOTE_ADDR: Fallback, may be proxy IP if behind a reverse proxy.
// phpcs:ignore WordPressVIPMinimum.Variables.ServerVariables.UserControlledHeaders, WordPressVIPMinimum.Variables.RestrictedVariables.cache_constraints___SERVER__REMOTE_ADDR__
$remote_addr = ! empty( $_SERVER['REMOTE_ADDR'] ) ? filter_var( wp_unslash( $_SERVER['REMOTE_ADDR'] ), FILTER_VALIDATE_IP ) : false;
if ( ! empty( $remote_addr ) ) {
return $remote_addr;
}
return '';
}
/**
* Strips the weight from a language code.
*
* @param string $str The language code.
*
* @return string The language code without the weight.
*/
function cf7a_strip_weight( string $str ): string {
$str = trim( $str );
if ( strpos( $str, ';' ) !== false ) {
$str = substr( $str, 0, strpos( $str, ';' ) );
}
return $str;
}
/**
* Generate an array of languages and locales based on the accept language header.
*
* @param string $accept_language The accept language header.
*
* @return string[] The array of language-locale codes.
*/
function cf7a_init_languages_locales_array( string $accept_language ): array {
return array_reduce(
explode( ',', $accept_language ),
function ( $res, $el ) {
$res[] = cf7a_strip_weight( $el );
return $res;
},
array()
);
}
/**
* It takes a string of comma-separated language codes, and returns an array of language codes
*
* @param string $languages_locales The Accept-Language header sent by the browser.
*
* @return array assoc array of languages and locales
*/
function cf7a_get_browser_languages_locales_array( string $languages_locales ): array {
$result = array_reduce(
explode( ',', $languages_locales ),
function ( $res, $el ) {
$el = cf7a_strip_weight( $el );
if ( strlen( $el ) >= 5 ) {
/* split into key: language , value: locale */
$l = explode( '-', $el );
$res['languages'][] = $l[0];
$res['locales'][] = $l[1];
} elseif ( strlen( $el ) === 2 && ctype_alpha( $el ) ) {
/* otherwise keep key:language, value: '' (any locale) */
if ( ctype_lower( $el ) ) {
$res['languages'][] = $el;
} elseif ( ctype_upper( $el ) ) {
$res['locales'][] = $el;
}
}
return $res;
},
array()
);
if ( ! empty( $result ) ) {
$result['languages'] = array_values( array_unique( $result['languages'] ) );
$result['locales'] = array_values( array_unique( $result['locales'] ) );
}
return $result;
}
/**
*
* Converts HTTP_ACCEPT_LANGUAGE into an array of languages
* this is a modified version of https://stackoverflow.com/a/33748742/5735847
*
* It takes a string like
* `en-US,en;q=0.9,de;q=0.8,es;q=0.7,fr;q=0.6,it;q=0.5,pt;q=0.4,ru;q=0.3,ja;q=0.2,zh-CN;q=0.1,zh-TW;q=0.1` and returns an
* array like `[ 'en', 'de', 'es', 'fr', 'it', 'pt', 'ru', 'ja', 'zh']`
*
* @param string $languages The Accept-Language header from the browser.
*
* @return array An array of languages.
*/
function cf7a_get_accept_language_array( $languages ) {
return array_values(
array_reduce(
explode( ',', str_replace( ' ', '', $languages ) ),
function ( $res, $el ) {
if ( strlen( $el ) === 5 ) {
$l = explode( '-', $el );
$res[ strtolower( $l[0] ) ] = $l[0];
} else {
$l = cf7a_strip_weight( $el );
if ( ctype_alpha( $l[0] ) && ctype_lower( $l[0] ) ) {
$res[ strtolower( $l[0] ) ] = $l[0];
}
}
return $res;
},
array()
)
);
}
/**
* Generates an array of accepted locales based on the given input.
*
* @param string $locales A comma-separated list of locales.
* @return array An array of accepted locales.
*/
function cf7a_get_accept_locales_array( $locales ) {
return array_values(
array_reduce(
explode( ',', str_replace( ' ', '', $locales ) ),
function ( $res, $el ) {
if ( strlen( $el ) === 5 ) {
$l = explode( '-', $el );
$res[ strtolower( $l[1] ) ] = $l[1];
} else {
$l = cf7a_strip_weight( $el );
if ( ctype_alpha( $l[0] ) && ctype_upper( $l[0] ) ) {
$res[ strtolower( $l[0] ) ] = $l[0];
}
}
return $res;
},
array()
)
);
}
/**
* It adds two new cron schedules to WordPress
*
* @param array $schedules This is the name of the hook that we're adding a schedule to.
*/
function cf7a_add_cron_steps( $schedules ) {
// phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval
return array_merge(
$schedules,
array(
'5min' => array(
'interval' => 300,
'display' => __( 'Every 5 Minutes', 'cf7-antispam' ),
),
'60sec' => array(
'interval' => 60,
'display' => __( 'Every 60 seconds', 'cf7-antispam' ),
),
)
);
}
// phpcs:ignore WordPress.WP.CronInterval.CronSchedulesInterval
add_filter( 'cron_schedules', 'cf7a_add_cron_steps' );
/**
* It adds a bunch of common honeypot input names to the list of honeypot input names.
*
* Returns the full candidate list (user-defined names merged with the legacy defaults).
* Callers that operate on a live form MUST subtract the form's own real field names via
* array_diff() before injecting or checking honeypot inputs, to avoid false positives.
*
* @param array $custom_names The array of input names to check for.
*
* @return array An array of possible input names.
*/
function cf7a_get_honeypot_input_names( $custom_names = array() ) {
$defaults = array(
'name',
'email',
'address',
'zip',
'town',
'phone',
'credit-card',
'ship-address',
'billing_company',
'billing_city',
'billing_country',
'email-address',
);
return array_values(
array_unique(
array_merge(
(array) $custom_names,
$defaults
)
)
);
}
/**
* It encrypts a string using the WordPress salt as the key
*
* @param string|int $value The value to encrypt.
* @param string $cipher The cipher method to use.
*
* @return string The encrypted value.
*/
function cf7a_crypt( $value, $cipher = 'aes-256-cbc' ) {
if ( ! extension_loaded( 'openssl' ) ) {
return $value;
}
// 1. Calculate the specific IV length required by this cipher
$iv_len = openssl_cipher_iv_length( $cipher );
// 2. Prepare the IV (handle 0-length ciphers like ECB)
$iv = '';
if ( $iv_len > 0 ) {
// Cut the salt to exactly the length required
$iv = substr( wp_salt( 'nonce' ), 0, $iv_len );
}
// 3. Encrypt using the dynamic IV
return openssl_encrypt( $value, $cipher, wp_salt( 'nonce' ), 0, $iv );
}
/**
* It decrypts the data.
*
* @param string $value The value to be encrypted.
* @param string $cipher The cipher method to use.
*
* @return string The decrypted value.
*/
function cf7a_decrypt( string $value, string $cipher = 'aes-256-cbc' ): string {
try {
if ( ! extension_loaded( 'openssl' ) ) {
return $value;
}
// 1. Calculate the specific IV length required by this cipher
$iv_len = openssl_cipher_iv_length( $cipher );
// 2. Prepare the IV (must match the one used during encryption)
$iv = '';
if ( $iv_len > 0 ) {
$iv = substr( wp_salt( 'nonce' ), 0, $iv_len );
}
// 3. Decrypt using the dynamic IV
return openssl_decrypt( $value, $cipher, wp_salt( 'nonce' ), 0, $iv );
} catch ( Exception $e ) {
return $value;
}
}
/**
* It returns the current time in microseconds.
*
* @return float The current time in microseconds.
*/
function cf7a_microtime_float() {
$time = explode( ' ', microtime() );
return (float) $time[0] + (float) $time[1];
}
/**
* It takes three numbers (red, green, and blue) and returns a hexadecimal color code
*
* @param int $r red.
* @param int $g green.
* @param int $b blue.
*
* @return string A hexadecimal color code.
*/
function cf7a_rgb2hex( $r, $g, $b ) {
return sprintf( '#%02x%02x%02x', (int) $r, (int) $g, (int) $b );
}
/**
* Used to display formatted d8 rating into flamingo inbound
*
* @param numeric $rating - the raw rating.
*
* @return string - html formatted rating
*/
function cf7a_format_rating( $rating ) {
if ( ! is_numeric( $rating ) ) {
return sprintf( '<span class="cf7a-rating-label cf7a-tag-none" style="background-color: #999"><b>%s</b></span>', __( 'none', 'cf7-antispam' ) );
}
$red = floor( 200 * $rating );
$green = floor( 200 * ( 1 - $rating ) );
$color = cf7a_rgb2hex( $red, $green, 0 );
return sprintf( '<span class="cf7a-rating-label" style="background-color: %s"><b>%s%% </b></span>', $color, round( $rating * 100 ) );
}
/**
* It takes a number and returns a color based on that number.
*
* @param numeric $rank The rank of the page.
*
* @return string an icon with a red color, that becomes greener when the rank is high
*/
function cf7a_format_status( $rank ) {
$rank = intval( $rank );
switch ( true ) {
case $rank < 0:
/* translators: warn because not yet banned but already listed */
$rank_clean = esc_html__( '⚠️', 'cf7-antispam' );
break;
case $rank > 100:
/* translators: champion of spammer (>100 mail) */
$rank_clean = esc_html__( '🏆', 'cf7-antispam' );
break;
default:
$rank_clean = $rank;
}
if ( $rank > 0 ) {
$green = intval( max( 200 - ( $rank * 2 ), 0 ) );
$color = cf7a_rgb2hex( 250, $green, 0 );
} else {
$color = '#aaa';
}
return sprintf( '<span class="ico" style="background-color: %s">%s</span>', $color, $rank_clean );
}
/**
* It takes an array and returns a string with the array's keys and values separated by a colon and a space, and each
* key/value pair separated by a semicolon and a space
*
* @param array $arr - the array of reasons to ban.
* @param bool $is_html - true to return an HTML string.
*
* @return string Compress arrays into "key:value; " pair
*/
function cf7a_compress_array( $arr, bool $is_html = false ): string {
if ( ! is_array( $arr ) ) {
// Handle string data
if ( is_string( $arr ) && ! empty( $arr ) ) {
return $arr;
}
return '';
}
$is_html = intval( $is_html );
return implode(
$is_html ? '<br /> ' : ', ',
array_map(
function ( $v, $k ) use ( $is_html ) {
// Handles values by type
if ( is_array( $v ) ) {
if ( empty( $v ) ) {
$v = '[]';
} else {
// Convert array to readable format
$v = '[' . implode(
', ',
array_map(
function ( $item ) {
return is_array( $item ) ? wp_json_encode( $item ) : (string) $item;
},
$v
)
) . ']';
}
} elseif ( is_object( $v ) ) {
$v = wp_json_encode( $v );
} elseif ( is_bool( $v ) ) {
$v = $v ? 'true' : 'false';
} elseif ( is_null( $v ) ) {
$v = 'null';
}//end if
// Handles HTML output
if ( $is_html ) {
return sprintf( '<b>%s</b>: %s', esc_html( $k ), esc_html( $v ) );
} else {
return sprintf( '%s: %s', $k, $v );
}
},
$arr,
array_keys( $arr )
)
);
}
/**
* If the string is not empty, and the log level is 0 or 1 and debug is on, or the log level is 2 and extended debug is
* on, then log the string
*
* @param string|array $log_data - The string/array to log.
* @param numeric $log_level 0 = log always, 1 = logging, 2 = only extended logging.
*
* @return void
*/
function cf7a_log( $log_data, $log_level = 0 ) {
if ( empty( $log_data ) ) {
return;
}
// Define visibility flags
$debug_enabled = defined( 'CF7ANTISPAM_DEBUG' ) && CF7ANTISPAM_DEBUG;
$extended_debug_enabled = defined( 'CF7ANTISPAM_DEBUG_EXTENDED' ) && CF7ANTISPAM_DEBUG_EXTENDED;
$should_log = false;
// Cascading logic
if ( 0 === $log_level ) {
$should_log = true;
} elseif ( 1 === $log_level && ( $debug_enabled || $extended_debug_enabled ) ) {
$should_log = true;
} elseif ( 2 === $log_level && $extended_debug_enabled ) {
$should_log = true;
}
if ( $should_log ) {
// Mask sensitive data if NOT in extended debug mode
$is_extended = defined( 'CF7ANTISPAM_DEBUG_EXTENDED' ) && CF7ANTISPAM_DEBUG_EXTENDED;
if ( is_string( $log_data ) && ! $is_extended ) {
// Hash IP addresses (IPv4 pattern)
$log_data = preg_replace_callback(
'/\b(?:\d{1,3}\.){3}\d{1,3}\b/',
function ( $matches ) {
return 'IP:' . substr( md5( $matches[0] ), 0, 8 );
},
$log_data
);
}
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
$output = is_string( $log_data ) ? $log_data : print_r( $log_data, true );
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
error_log( CF7ANTISPAM_LOG_PREFIX . $output );
}//end if
}
/**
* It takes a string of metadata and unquote it
* the part between the first two characters and the last two characters.
*
* @param string $tag The raw message string.
*
* @return string the clean tag string
*/
function cf7a_get_mail_meta( $tag ) {
return is_string( $tag ) ? substr( $tag, 2, -2 ) : '';
}
/**
* If the message tag contains a space, it's a multiple meta tag,
* so split it up and return the value of the meta-tag
*
* @param array $posted_data The form data array.
* @param string $message_tag The tag of the field you want to retrieve.
* @param string $explode_pattern Used to split multiple cf7 user tags.
*
* @return string | false the field requested
*/
function cf7a_maybe_split_mail_meta( array $posted_data, string $message_tag, string $explode_pattern = '] [' ) {
if ( strpos( $message_tag, $explode_pattern ) !== false ) {
$message = '';
foreach ( explode( $explode_pattern, $message_tag ) as $message_tag_chunk ) {
$tag_chunk = sanitize_title( $message_tag_chunk );
if ( ! empty( $posted_data[ $tag_chunk ] ) ) {
$message .= sanitize_title( $tag_chunk ) . ': ' . sanitize_textarea_field( $posted_data[ $tag_chunk ] ) . "\r\n";
}
}
return $message;
}
return isset( $posted_data[ $message_tag ] ) ? sanitize_textarea_field( $posted_data[ $message_tag ] ) : '';
}
/**
* This is a PHP function that takes in a string array and returns an unsigned integer array.
*
* @param array $str_array The string array to be converted.
*
* @return array $num_array The unsigned integer array.
*/
function cf7a_str_array_to_uint_array( $str_array ) {
return array_unique(
array_filter(
$str_array,
function ( $value ) {
return is_int( $value ) || ( is_numeric( $value ) && $value > 0 && intval( $value ) === $value );
}
)
);
}