-
Notifications
You must be signed in to change notification settings - Fork 12
/
class-cf7-repeatable-fields.php
349 lines (318 loc) · 10.8 KB
/
class-cf7-repeatable-fields.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
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
<?php
/**
* Plugin Main Class File
*
* @package CF7_Repeatable_Fields
*/
defined( 'ABSPATH' ) || exit;
/**
* Main Class
*/
class CF7_Repeatable_Fields {
/**
* The only instance of the class.
*
* @var object
*/
protected static $instance = null;
/**
* Name of the shortcode responsible for repeating the group.
*
* @var string
*/
protected $shortcode = 'field_group';
/**
* Form groups, indexed by their ids. Each group has
* `tags` (an array of WPCF7_FormTag) and
* `raw`, the forms as created by the user.
*
* @var array
*/
protected $groups = array();
/**
* Class constructor. Run only once (Singleton).
*/
private function __construct() {
add_shortcode( $this->shortcode, array( $this, 'shortcode_render' ) );
add_action( 'wpcf7_contact_form', array( $this, 'wpcf7_contact_form' ) );
add_action( 'wpcf7_enqueue_scripts', array( $this, 'wpcf7_enqueue_scripts' ) );
}
/**
* The group shortcode. Generate the `<div>` element with fields and
* set `$this->tags`.
*
* @param array $atts Group attributes. Should have a value wo attribute to be used as the group ID.
* @param string $content Everything inside the shortcode. Hopefully CF7 fields (raw tags).
* @return string $content with the add and remove buttons wrapped by a `div`.
*/
public function shortcode_render( $atts, $content ) {
// Respect classes sent by user, but add the necessary class for js.
$atts = ( empty( $atts ) ) ? array() : $atts;
$atts['class'] = ( isset( $atts['class'] ) ) ? $atts['class'] : '';
$atts['class'] = 'wpcf7-field-groups ' . $atts['class'];
$group_id = '';
$atts = array_map(
function( $att, $value ) use ( &$group_id ) {
// WordPress sets numeric atts if the `attr="value"` format isn't used.
if ( is_int( $att ) ) {
if ( false === strpos( $value, ':' ) ) {
$att = 'data-wpcf7-group-id';
$group_id = $value;
} else {
// User can send attributes in the same format of CF7, i.e., `attr:value`.
list( $att, $value ) = explode( ':', $value );
}
}
return sprintf( '%s="%s"', $att, esc_attr( $value ) );
},
array_keys( $atts ),
$atts
);
// Abort if there is no group id.
if ( empty( $group_id ) ) {
return sprintf(
/* translators: Format to use surrounded by code tag */
'<p>' . __( 'You need to set an ID to this group. Use %s format.', 'cf7-repeatable-fields' ) . '</p>',
"<code>[{$this->shortcode} your_custom_id]</code>"
);
}
$form_tags_manager = WPCF7_FormTagsManager::get_instance();
$this->groups[ $group_id ] = array(
'tags' => $form_tags_manager->scan( $content ),
'raw' => $content,
);
// Add and remove group buttons. TODO: make this available from form edit screen.
/**
* Filters the add button attributes. Additional classes and text, so far.
*
* @param array $add_button_atts Array of strings with `group_id`, `additional_classes` and
* `text` as indexes.
*/
$add_button_atts = apply_filters(
'wpcf7_field_group_add_button_atts',
array(
'group_id' => $group_id,
'additional_classes' => '',
'text' => '+',
)
);
/**
* Filters the whole add group button. This way developers can wrap it with another element.
*
* @param string $button_html The HTML of the add button.
* @param string $group_id Current group ID.
*/
$add_button = apply_filters(
'wpcf7_field_group_add_button',
"<button type='button' class='wpcf7-field-group-add {$add_button_atts['additional_classes']}'>" .
$add_button_atts['text'] .
'</button>',
$group_id
);
/**
* Filters the remove button attributes. Additional classes and text, so far.
*
* @param array $remove_button_atts Array of strings with `group_id`, `additional_classes` and
* `text` as indexes.
*/
$remove_button_atts = apply_filters(
'wpcf7_field_group_remove_button_atts',
array(
'group_id' => $group_id,
'additional_classes' => '',
'text' => '-',
)
);
/**
* Filters the whole remove group button. This way developers can wrap it with another element.
*
* @param string $button_html The HTML of the remove button.
* @param string $group_id Current group ID.
*/
$remove_button = apply_filters(
'wpcf7_field_group_remove_button',
"<button type='button' class='wpcf7-field-group-remove {$remove_button_atts['additional_classes']}'>" .
$remove_button_atts['text'] .
'</button>',
$group_id
);
// Remove any attribute that is not allowed by CF7.
$open_tag = wpcf7_kses( '<div ' . implode( ' ', $atts ) . '>' );
/**
* Filters the group content.
*
* @since 2.0.2
* @param string $group_content Group content HTML
* @param array $atts Shortcode attributes
* @param string $group_id Current group ID.
*/
$group_content = apply_filters(
'wpcf7_field_group_content',
'<div class="wpcf7-field-group">' .
do_shortcode( $content ) .
$remove_button .
$add_button .
'<input type="hidden" class="wpcf7-field-group-count" name="_wpcf7_groups_count[' . $group_id . ']" value="1" />' .
'</div>',
$atts,
$group_id
);
return $open_tag . $group_content . '</div>';
}
/**
* Enqueue the necessary JS for groups manipulation.
*/
public function wpcf7_enqueue_scripts() {
$file = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ?
'assets/js/scripts.js' :
'dist/scripts.js';
wp_enqueue_script(
'wpcf7-field-group-script',
plugin_dir_url( CF7_REPEATABLE_FIELDS_FILE ) . $file,
array( 'jquery' ),
CF7_REPEATABLE_FIELDS_VERSION,
true
);
}
/**
* Change the Contact Form attributes. This way we make CF7 process this as
* the form had several groups all the time.
*
* Here we take the fields and change their names. Example:
* A `[your-field]` field becomes `[your-field__1]` and, if it's needed,
* we append the necessary `[your-field__2]`, `[your-field__3]` and so on. That
* way CF7 validates the field as a normal one.
*
* @param WPCF7_ContactForm $contact_form The Contact Form object.
*/
public function wpcf7_contact_form( $contact_form ) {
// Don't mess up when user is editing the form.
if ( is_admin() ) {
return;
}
// This enables shortcode in Contact Form form. Side effects?
$form = do_shortcode( $contact_form->prop( 'form' ) );
$mail = $contact_form->prop( 'mail' );
$mail_2 = $contact_form->prop( 'mail_2' );
// Post info sanitization.
$groups_count = $this->sanitize_groups_count();
/*
* We only make our magic when user is sending the form.
* There is no need to change anything when showing it for the first time.
*/
if ( count( $this->groups ) && ! empty( $groups_count ) ) {
foreach ( $groups_count as $group_id => $group_sent_count ) {
// Change the `form` property.
$form_raw_tags = $this->groups[ $group_id ]['raw'];
$form_tags_first_replaced = $form_raw_tags;
foreach ( $this->groups[ $group_id ]['tags'] as $tag ) {
$tag_type = preg_quote( $tag->type, '/' );
$tag_name = preg_quote( $tag->name, '/' );
// Change the original `name` to `name__1`.
$form_tags_first_replaced = preg_replace( "/\[{$tag_type}(.*?){$tag_name}/", "[{$tag->type}\\1{$tag->name}__1", $form_tags_first_replaced );
}
$form_tags_replaced = $form_tags_first_replaced;
for ( $i = 2; $i <= $group_sent_count; $i++ ) {
// Change the `name__1` to `name__$i`.
$form_tags_replaced .= preg_replace( '/__1(\s|\])/', "__{$i}$1", $form_tags_first_replaced );
}
$form = str_replace(
$form_raw_tags,
$form_tags_replaced,
$form
);
// Change the `mail` property. Users can use `[group_index]` inside a group to show it's number.
$mail['body'] = $this->replace_mail_field_groups( $group_id, $group_sent_count, $mail['body'] );
$mail_2['body'] = $this->replace_mail_field_groups( $group_id, $group_sent_count, $mail_2['body'] );
}
}
// Set up modified properties. `form` here already was `do_shortcode`'ed.
$contact_form->set_properties(
array(
'form' => $form,
'mail' => $mail,
'mail_2' => $mail_2,
)
);
}
/**
* Replace a field group in mail bodies
*
* @param string $group_id The group ID.
* @param int $group_sent_count Groups sent count.
* @param string $mail_body The text set as body by users in CF7. User for main mail and mail 2.
* @return string `$mail_body` with group replaced.
*/
private function replace_mail_field_groups( $group_id, $group_sent_count, $mail_body ) {
$group_name = preg_quote( $group_id, '/' );
$group_in_mail = preg_match_all(
"/\[{$group_name}\](.*?)\[\/{$group_name}\]/s",
$mail_body,
$matches
);
if ( $group_in_mail ) {
foreach ( $matches[1] as $i => $group_raw_content ) {
$group_tags_first_replaced = str_replace(
'[group_index]',
'[group_index__1]',
$group_raw_content
);
foreach ( $this->groups[ $group_id ]['tags'] as $tag ) {
$tag_name_regex = preg_quote( $tag->name, '/' );
// Change the original `name` to `name__1`.
// Date fields accept `_format_` as a prefix.
$group_tags_first_replaced = preg_replace(
"/\[(_format_)?{$tag_name_regex}(\s|\])/",
"[$1{$tag->name}__1$2",
$group_tags_first_replaced
);
}
$group_tags_replaced = $group_tags_first_replaced;
for ( $j = 2; $j <= $group_sent_count; $j++ ) {
// Change the `name__1` to `name__$i`.
$group_tags_replaced .= preg_replace(
'/__1(\s|\])/',
"__{$j}$1",
$group_tags_first_replaced
);
}
$group_tags_replaced = preg_replace(
'/\[group_index__([0-9]*)\]/',
'\\1',
$group_tags_replaced
);
$mail_body = str_replace(
$matches[0][ $i ],
$group_tags_replaced,
$mail_body
);
}
}
return $mail_body;
}
/**
* Sanitization method of the `_wpcf7_groups_count` hidden input.
*
* @return array
*/
private function sanitize_groups_count() {
// phpcs:disable WordPress.Security.NonceVerification.Missing -- CF7 Handles this.
// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$groups_count = ( isset( $_POST['_wpcf7_groups_count'] ) ) ? wp_unslash( (array) $_POST['_wpcf7_groups_count'] ) : array();
$groups_count = array_map( 'sanitize_text_field', wp_unslash( (array) $groups_count ) );
// phpcs:enable WordPress.Security.NonceVerification.Missing
// phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
return $groups_count;
}
/**
* SINGLETON. Return the single class instance.
*
* @return object the single instance of the class.
*/
public static function get_instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
}