forked from gravitywiz/snippet-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gw-unique-id-exclude-characters.php
83 lines (77 loc) · 2.44 KB
/
gw-unique-id-exclude-characters.php
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
<?php
/**
* Gravity Wiz // Exclude characters from GPUID
*
* Allows you to exclude characters from unique IDs generated using GPUID.
*
* @version 1.2
* @author Eihab Ibrahim <[email protected]>
* @license GPL-2.0+
* @link http://gravitywiz.com/calculate-number-of-days-between-two-dates/
* @copyright 2020 Gravity Wiz
*/
class GWExcludeUIDChars {
/**
* GWExcludeUIDChars Constructor
*
* Expects an $args named array with the following keys=>values:
* 'form_id': ID of the GF form to perform replacements in
* 'field_id': GPUID Input ID
* 'exclude': String containing characters to exclude
* 'sitewide': [optional] Boolean, set to true to apply to all GPUIDs
*
* Example usage in functions.php:
* new GWExcludeUIDChars( array(
* 'form_id' => 11,
* 'field_id' => 1,
* 'exclude' => 'li0o'
* ) );
*/
public function __construct( $args ) {
extract( wp_parse_args( $args, array(
'form_id' => false,
'field_id' => false,
'exclude' => false,
'sitewide' => false,
) ) );
if ( ! $form_id || ! $field_id || ! $exclude ) {
if ( ! $sitewide || ! $exclude ) {
return;
}
}
$this->form_id = $form_id;
$this->field_id = $field_id;
$this->sitewide = $sitewide;
$this->exclude = str_split( $exclude );
add_filter( 'gpui_unique_id', array( &$this, 'exclude_action' ), 10, 3 );
}
public function exclude_action( $unique, $form_id, $field_id ) {
if ( ! $this->sitewide && ( intval( $form_id ) !== $this->form_id || intval( $field_id ) !== $this->field_id ) ) {
return $unique;
}
// Setup valid replacements array
$alphanumeric = array_merge( range( 'a', 'z' ), range( 0, 9 ) );
$alphanumeric = array_values( array_diff( $alphanumeric, $this->exclude ) );
$alphanumeric_length = count( $alphanumeric );
$unique = str_split( $unique );
for ( $i = 0, $max = count( $unique ); $i < $max; $i++ ) {
// Replace excluded characters with a random valid substitute
if ( in_array( $unique[ $i ], $this->exclude, true ) ) {
$unique[ $i ] = $alphanumeric[ rand( 0, $alphanumeric_length ) ];
}
}
return join( $unique );
}
}
// Uncomment and customize/duplicate the following lines:
// new GWExcludeUIDChars( array(
// 'form_id' => 11,
// 'field_id' => 1,
// 'sitewide' => false,
// 'exclude' => 'li0o'
// ) );
// To apply exclusions site-wide use the following:
// new GWExcludeUIDChars( array(
// 'sitewide' => true,
// 'exclude' => 'li0o'
// ) );