-
Notifications
You must be signed in to change notification settings - Fork 101
/
class-fieldmanager-field.php
1492 lines (1337 loc) · 44.4 KB
/
class-fieldmanager-field.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
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Class file for Fieldmanager_Field
*
* @package Fieldmanager
*/
/**
* Abstract base class containing core functionality for Fieldmanager fields.
*
* Fields are UI elements that allow a person to interact with data.
*/
abstract class Fieldmanager_Field {
/**
* If true, throw exceptions for illegal behavior.
*
* @var bool
*/
public static $debug = FM_DEBUG;
/**
* Indicate that the base FM assets have been enqueued so we only do it once.
*
* @var bool
*/
public static $enqueued_base_assets = false;
/**
* How many of these fields to display, 0 for no limit.
*
* @var int
*/
public $limit = 1;
/**
* This is no longer used.
*
* @deprecated This argument will have no impact. It only remains to avoid
* throwing exceptions in code that used it previously.
* @var int
*/
public $starting_count;
/**
* How many of these fields to display at a minimum, if $limit != 1. If
* $limit == $minimum_count, the "add another" button and the remove tool
* will be hidden.
*
* @var int
*/
public $minimum_count = 0;
/**
* How many empty fields to display if $limit != 1 when the total fields in
* the loaded data + $extra_elements > $minimum_count.
*
* @var int
*/
public $extra_elements = 1;
/**
* Text for add more button.
*
* @var string
*/
public $add_more_label = '';
/**
* The name of the form element, as in 'foo' in `<input name="foo" />`.
*
* @var string
*/
public $name = '';
/**
* Label to use for form element.
*
* @var string
*/
public $label = '';
/**
* If true, the label and the element will display on the same line. Some
* elements may not support this.
*
* @var bool
*/
public $inline_label = false;
/**
* If true, the label will be displayed after the element.
*
* @var bool
*/
public $label_after_element = false;
/**
* Description for the form element.
*
* @var string
*/
public $description = '';
/**
* If true, the description will be displayed after the element.
*
* @var bool
*/
public $description_after_element = true;
/**
* Extra HTML attributes to apply to the form element. Use boolean true to
* apply a standalone attribute, e.g. 'required' => true.
*
* @var string|bool|array
*/
public $attributes = array();
/**
* CSS class for form element.
*
* @var string
*/
public $field_class = 'element';
/**
* Repeat the label for each element if $limit > 1.
*
* @var bool
*/
public $one_label_per_item = true;
/**
* Allow draggable sorting if $limit > 1.
*
* @var bool
*/
public $sortable = false;
/**
* HTML element to use for label.
*
* @var string
*/
public $label_element = 'div';
/**
* Function to use to sanitize input.
*
* @var callable
*/
public $sanitize = 'sanitize_text_field';
/**
* Functions to use to validate input.
*
* @var array Callables.
*/
public $validate = array();
/**
* Validation rule(s) from jQuery used to validate this field, entered as a string or associative array.
* These rules will be automatically converted to the appropriate Javascript format.
* For more information see http://jqueryvalidation.org/documentation/
*
* @var string|array
*/
public $validation_rules;
/**
* Validation messages from jQuery used by the rule(s) defined for this field, entered as a string or associative array.
* These rules will be automatically converted to the appropriate Javascript format.
* Any messages without a corresponding rule will be ignored.
* For more information see http://jqueryvalidation.org/documentation/
*
* @var string|array
*/
public $validation_messages;
/**
* Makes the field required on WordPress context forms that already have built-in validation.
* This is necessary only for the fields used with the term add context.
*
* @var bool
*/
public $required = false;
/**
* Data type this element is used in, generally set internally.
*
* @var string
*/
public $data_type = null;
/**
* ID for $this->data_type, eg $post->ID, generally set internally.
*
* @var int
*/
public $data_id = null;
/**
* Fieldmanager context handling data submitted with this field. Generally set internally.
*
* @var ?Fieldmanager_Context
*/
public $current_context = null;
/**
* If true, save empty elements to DB (if $this->limit != 1; single elements
* are always saved).
*
* @var bool
*/
public $save_empty = false;
/**
* Do not save this field (useful for fields which handle saving their own data)
*
* @var bool
*/
public $skip_save = false;
/**
* Save this field additionally to an index.
*
* @var bool
*/
public $index = false;
/**
* Save the fields to their own keys (only works in some contexts). Default
* is true.
*
* @var bool
*/
public $serialize_data = true;
/**
* Optionally generate field from datasource. Used by Fieldmanager_Autocomplete
* and Fieldmanager_Options.
*
* @var Fieldmanager_Datasource
*/
public $datasource = null;
/**
* Field name and value on which to display element. Sample:
*
* $element->display_if = array(
* 'src' => 'display-if-src-element',
* 'value' => 'display-if-src-value',
* );
*
* Multiple values are allowed if comma-separated. Sample:
*
* $element->display_if = array(
* 'src' => 'display-if-src-element',
* 'value' => 'display-if-src-value1,display-if-src-value2'
* );
*
* @var array
*/
public $display_if = array();
/**
* Where the new item should to added (top/bottom) of the stack. Used by Add
* Another button "top|bottom".
*
* @var string
*/
public $add_more_position = 'bottom';
/**
* If true, remove any default meta boxes that are overridden by Fieldmanager
* fields.
*
* @var bool
*/
public $remove_default_meta_boxes = false;
/**
* The path to the field template.
*
* @var string Template
*/
public $template = null;
/**
* If $remove_default_meta_boxes is true, this array will be populated with
* the list of default meta boxes to remove.
*
* @var array
*/
public $meta_boxes_to_remove = array();
/**
* The default value for the field, if unset.
*
* @var mixed Default value
*/
public $default_value = null;
/**
* Function that parses an index value and returns an optionally modified value.
*
* @var callable
*/
public $index_filter = null;
/**
* Input type, mainly to support HTML5 input types.
*
* @var string
*/
public $input_type = 'text';
/**
* Custom escaping for labels, descriptions, etc. Associative array of
* $field => $callable arguments, for example:
*
* 'escape' => array( 'label' => 'wp_kses_post' )
*
* @var array
*/
public $escape = array();
/**
* If $this->limit > 1, which element in sequence are we currently rendering?
*
* @var int
*/
protected $seq = 0;
/**
* If $is_proto is true, we're rendering the prototype element for a field
* that can have infinite instances.
*
* @var bool
*/
protected $is_proto = false;
/**
* Parent element, if applicable. Would be a Fieldmanager_Group unless
* third-party plugins support this.
*
* @var Fieldmanager_Field
*/
protected $parent = null;
/**
* Render this element in a tab?
*
* @todo Add extra wrapper info rather than this specific.
*
* @var bool
*/
protected $is_tab = false;
/**
* Have we added this field as a meta box yet?
*
* @var bool
*/
private $meta_box_actions_added = false;
/**
* Whether or not this field is present on the attachment edit screen.
*
* @var bool
*/
public $is_attachment = false;
/**
* The global sequence of elements.
*
* @var int Global Sequence
*/
private static $global_seq = 0;
/**
* Generate HTML for the form element itself. Generally should be just one
* tag, no wrappers.
*
* @param mixed $value The value of the element.
* @return string HTML for the element.
*/
public function form_element( $value ) {
if ( ! $this->template ) {
$tpl_slug = strtolower( str_replace( 'Fieldmanager_', '', get_class( $this ) ) );
$this->template = fieldmanager_get_template( $tpl_slug );
}
ob_start();
// phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable -- baseline
include $this->template;
return ob_get_clean();
}
/**
* Superclass constructor, just populates options and sanity-checks common elements.
* It might also die, but only helpfully, to catch errors in development.
*
* @param string|array $label The field label.
* @param array $options The field options.
*/
public function __construct( $label = '', $options = array() ) {
$this->set_options( $label, $options );
// A post can only have one parent, so if this saves to post_parent and
// it's repeatable, we're doing it wrong.
if ( $this->datasource && ! empty( $this->datasource->save_to_post_parent ) && $this->is_repeatable() ) {
_doing_it_wrong( 'Fieldmanager_Datasource_Post::$save_to_post_parent', esc_html__( 'A post can only have one parent, therefore you cannot store to post_parent in repeatable fields.', 'fieldmanager' ), '1.0.0' );
$this->datasource->save_to_post_parent = false;
$this->datasource->only_save_to_post_parent = false;
}
// Only enqueue base assets once, and only when we have a field.
if ( ! self::$enqueued_base_assets ) {
fm_add_script( 'fieldmanager_script', 'js/fieldmanager.js', array( 'fm_loader', 'jquery', 'jquery-ui-sortable' ), FM_VERSION, false, 'fm' );
fm_add_style( 'fieldmanager_style', 'css/fieldmanager.css', array(), FM_VERSION );
self::$enqueued_base_assets = true;
}
}
/**
* Build options into properties and throw errors if developers add an unsupported opt.
*
* @throws FM_Developer_Exception If an option is set but not defined in this class or the child class.
* @throws FM_Developer_Exception If an option is set but not public.
*
* @param string|array $label The field label. A provided string sets $options['label'], while an array sets $options, overriding any existing data in $options.
* @param array $options The field options.
*/
public function set_options( $label, $options ) {
if ( is_array( $label ) ) {
$options = $label;
} else {
$options['label'] = $label;
}
// Get all the public properties for this object.
$properties = call_user_func( 'get_object_vars', $this );
foreach ( $options as $key => $value ) {
if ( array_key_exists( $key, $properties ) ) {
$this->$key = $value;
} elseif ( self::$debug ) {
$message = sprintf(
/* translators: 1: option key, 2: field class, 3: field name */
__( 'You attempted to set a property "%1$s" that is nonexistent or invalid for an instance of "%2$s" named "%3$s".', 'fieldmanager' ),
$key,
get_class( $this ),
! empty( $options['name'] ) ? $options['name'] : 'NULL'
);
throw new FM_Developer_Exception( esc_html( $message ) );
}
}
// If this is a single field with a limit of 1, serialize_data has no impact.
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( ! $this->serialize_data && ! $this->is_group() && 1 == $this->limit ) {
$this->serialize_data = true;
}
// Cannot use serialize_data => false with index => true.
if ( ! $this->serialize_data && $this->index ) {
throw new FM_Developer_Exception( esc_html__( 'You cannot use `"serialize_data" => false` with `"index" => true`', 'fieldmanager' ) );
}
}
/**
* Generates all markup needed for all form elements in this field.
* Could be called directly by a plugin or theme.
*
* @since 1.3.0 Added the 'fm-display-if' class for fields using display-if.
*
* @param mixed|mixed[]|null $values The current value or values for this
* element, or an associative array of
* the values of this element's children.
* Can be null if no value exists.
* @return string HTML for all form elements.
*/
public function element_markup( $values = array() ) {
$values = $this->preload_alter_values( $values );
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 1 != $this->limit ) {
// count() generates a warning when passed non-countable values in PHP 7.2.
if ( is_scalar( $values ) ) {
$count_values = 1;
} elseif ( ! is_array( $values ) && ! ( $values instanceof \Countable ) ) {
$count_values = 0;
} else {
$count_values = count( $values );
}
$max = max( $this->minimum_count, $count_values + $this->extra_elements );
// Ensure that we don't display more fields than we can save.
if ( $this->limit > 1 && $max > $this->limit ) {
$max = $this->limit;
}
} else {
$max = 1;
}
$classes = array( 'fm-wrapper', 'fm-' . $this->name . '-wrapper' );
$fm_wrapper_attrs = array();
if ( $this->sortable ) {
$classes[] = 'fmjs-sortable';
}
$classes = array_merge( $classes, $this->get_extra_element_classes() );
$out = '';
/*
* If this element is part of tabbed output, there needs to be a wrapper
* to contain the tab content.
*/
if ( $this->is_tab ) {
$out .= sprintf(
'<div id="%s-tab" class="wp-tabs-panel"%s>',
esc_attr( $this->get_element_id() ),
( $this->parent->child_count > 0 ) ? ' style="display: none"' : ''
);
}
// Find the array position of the "counter" (e.g. in element[0], [0] is the counter, thus the position is 1).
$html_array_position = 0; // default is no counter; i.e. if $this->limit = 0.
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 1 != $this->limit ) {
$html_array_position = 1; // base situation is formname[0], so the counter is in position 1.
if ( $this->parent ) {
$parent = $this->parent;
while ( $parent ) {
$html_array_position++; // one more for having a parent (e.g. parent[this][0]).
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 1 != $parent->limit ) { // and another for the parent having multiple (e.g. parent[0][this][0]).
$html_array_position++;
}
$parent = $parent->parent; // parent's parent; root element has null parent which breaks while loop.
}
}
}
// Checks to see if element has display_if data values, and inserts the data attributes if it does.
if ( isset( $this->display_if ) && ! empty( $this->display_if ) ) {
$classes[] = 'fm-display-if';
// For backwards compatibility.
$classes[] = 'display-if';
$fm_wrapper_attrs['data-display-src'] = $this->display_if['src'];
$fm_wrapper_attrs['data-display-value'] = $this->display_if['value'];
}
$fm_wrapper_attr_string = '';
foreach ( $fm_wrapper_attrs as $attr => $val ) {
$fm_wrapper_attr_string .= sprintf( '%s="%s" ', sanitize_key( $attr ), esc_attr( $val ) );
}
$out .= sprintf(
'<div class="%s" data-fm-array-position="%d" %s>',
esc_attr( implode( ' ', $classes ) ),
absint( $html_array_position ),
$fm_wrapper_attr_string
);
// For lists of items where $one_label_per_item = False, the label should go before the elements.
if ( ! empty( $this->label ) && ! $this->one_label_per_item ) {
$out .= $this->get_element_label( array( 'fm-label-for-list' ) );
}
/**
* Filters field markup before adding markup for its form elements.
*
* @since 0.1.0
* @since 1.0.0 The `$values` parameter was added.
*
* @param string $out Field markup.
* @param Fieldmanager_Field $this Field instance.
* @param mixed|mixed[]|null $values Current element value or values, if any.
*/
$out = apply_filters( 'fm_element_markup_start', $out, $this, $values );
/**
* Filters a specific field's markup before adding markup for its form elements.
*
* The dynamic portion of the hook name, `$this->name`, refers to the field's `$name` property.
*
* @since 1.2.0
*
* @param string $out Field markup.
* @param Fieldmanager_Field $this Field instance.
* @param mixed|mixed[]|null $values Current element value or values, if any.
*/
$out = apply_filters( "fm_element_markup_start_{$this->name}", $out, $this, $values );
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( ( 0 == $this->limit || ( $this->limit > 1 && $this->limit > $this->minimum_count ) ) && 'top' == $this->add_more_position ) {
$out .= $this->add_another();
}
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 1 != $this->limit ) {
$out .= $this->single_element_markup( null, true );
}
for ( $i = 0; $i < $max; $i++ ) {
$this->seq = $i;
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 1 == $this->limit ) {
$value = $values;
} else {
$value = isset( $values[ $i ] ) ? $values[ $i ] : null;
}
$out .= $this->single_element_markup( $value );
}
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( ( 0 == $this->limit || ( $this->limit > 1 && $this->limit > $this->minimum_count ) ) && 'bottom' == $this->add_more_position ) {
$out .= $this->add_another();
}
/**
* Filters field markup after adding markup for its form elements.
*
* @since 0.1.0
* @since 1.0.0 The `$values` parameter was added.
*
* @param string $out Field markup.
* @param Fieldmanager_Field $this Field instance.
* @param mixed|mixed[]|null $values Current element value or values, if any.
*/
$out = apply_filters( 'fm_element_markup_end', $out, $this, $values );
/**
* Filters a specific field's markup after adding markup for its form elements.
*
* The dynamic portion of the hook name, `$this->name`, refers to the field's `$name` property.
*
* @since 1.2.0
*
* @param string $out Field markup.
* @param Fieldmanager_Field $this Field instance.
* @param mixed|mixed[]|null $values Current element value or values, if any.
*/
$out = apply_filters( "fm_element_markup_end_{$this->name}", $out, $this, $values );
$out .= '</div>';
// Close the tab wrapper if one exists.
if ( $this->is_tab ) {
$out .= '</div>';
}
return $out;
}
/**
* Generate wrappers and labels for one form element. Is called by
* `element_markup()`, calls `form_element()`.
*
* @see Fieldmanager_Field::element_markup()
* @see Fieldmanager_Field::form_element()
*
* @param mixed|mixed[]|null $value Single element value, if any.
* @param bool $is_proto True to generate a prototype element
* for Javascript.
* @return string HTML for a single form element.
*/
public function single_element_markup( $value = null, $is_proto = false ) {
if ( $is_proto ) {
$this->is_proto = true;
}
$out = '';
$classes = array( 'fm-item', 'fm-' . $this->name );
self::$global_seq++;
// Drop the fm-group class to hide inner box display if no label is set.
if ( ! ( $this->is_group() && ( ! isset( $this->label ) || empty( $this->label ) ) ) ) {
$classes[] = 'fm-' . $this->field_class;
}
// Check if the required attribute is set. If so, add the class.
if ( $this->required ) {
$classes[] = 'form-required';
}
if ( ! $this->is_group() && ! $this->is_tab ) {
$classes[] = 'fm-field';
}
if ( ! $this->is_group() && $this->sortable ) {
$classes[] = 'fm-sortable-field';
if ( ( ! $this->one_label_per_item || empty( $this->label ) ) && empty( $this->description ) ) {
$classes[] = 'fm-no-labels';
}
}
if ( $is_proto ) {
$classes[] = 'fmjs-proto';
}
if ( $this->is_group() && 'vertical' === $this->tabbed ) {
$classes[] = 'fm-tabbed-vertical';
}
$classes = apply_filters( 'fm_element_classes', $classes, $this->name, $this );
$out .= sprintf( '<div class="%s">', esc_attr( implode( ' ', $classes ) ) );
$label = $this->get_element_label();
$render_label_after = false;
/*
* Hide the label if it is empty or if this is a tab since it would duplicate
* the title from the tab label.
*/
if ( ! empty( $this->label ) && ! $this->is_tab && $this->one_label_per_item ) {
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 1 != $this->limit ) {
$out .= $this->wrap_with_multi_tools( $label, array( 'fmjs-removable-label' ) );
} elseif ( ! $this->label_after_element ) {
$out .= $label;
} else {
$render_label_after = true;
}
}
if ( ! empty( $this->description ) && ! $this->description_after_element && ! $this->is_group() ) {
$out .= sprintf( '<div class="fm-item-description">%s</div>', $this->escape( 'description' ) );
}
if ( null === $value && null !== $this->default_value ) {
$value = $this->default_value;
}
$form_element = $this->form_element( $value );
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 1 != $this->limit && ( ! $this->one_label_per_item || empty( $this->label ) ) ) {
$out .= $this->wrap_with_multi_tools( $form_element );
} else {
$out .= $form_element;
}
if ( $render_label_after ) {
$out .= $label;
}
if ( ! empty( $this->description ) && $this->description_after_element && ! $this->is_group() ) {
$out .= sprintf( '<div class="fm-item-description">%s</div>', $this->escape( 'description' ) );
}
$out .= '</div>';
if ( $is_proto ) {
$this->is_proto = false;
}
return $out;
}
/**
* Alter values before rendering.
*
* @param mixed|mixed[]|null $values The current value or values for this element, if any.
* @return mixed|mixed[]|null The altered value.
*/
public function preload_alter_values( $values ) {
return apply_filters( 'fm_preload_alter_values', $values, $this );
}
/**
* Wrap a chunk of HTML with "remove" and "move" buttons if applicable.
*
* @param string $html HTML to wrap.
* @param array $classes An array of classes.
* @return string Wrapped HTML.
*/
public function wrap_with_multi_tools( $html, $classes = array() ) {
$classes[] = 'fmjs-removable';
$out = sprintf( '<div class="%s">', implode( ' ', $classes ) );
$handle = '';
if ( $this->sortable ) {
if ( ( $this->one_label_per_item || ! empty( $this->label ) ) && ! in_array( 'fmjs-removable-label', $classes, true ) && empty( $this->description ) ) {
$classes[] = 'fmjs-removable-sort';
}
$handle = $this->get_sort_handle();
}
$out .= $handle;
$out .= '<div class="fmjs-removable-element">';
$out .= $html;
$out .= '</div>';
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 0 == $this->limit || $this->limit > $this->minimum_count ) {
$out .= $this->get_remove_handle();
}
$out .= '</div>';
return $out;
}
/**
* Get HTML form name (e.g. questions[answer]).
*
* @param string $multiple Multiple fields.
* @return string Form name.
*/
public function get_form_name( $multiple = '' ) {
$tree = $this->get_form_tree();
$name = '';
foreach ( $tree as $level => $branch ) {
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 0 == $level ) {
$name .= $branch->name;
} else {
$name .= '[' . $branch->name . ']';
}
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 1 != $branch->limit ) {
$name .= '[' . $branch->get_seq() . ']';
}
}
return $name . $multiple;
}
/**
* Recursively build path to this element, e.g. [grandparent, parent, this].
*
* @return array $tree The form tree of parents.
*/
public function get_form_tree() {
$tree = array();
if ( $this->parent ) {
$tree = $this->parent->get_form_tree();
}
$tree[] = $this;
return $tree;
}
/**
* Get the ID for the form element itself, uses $this->seq (e.g. which position is this element in).
* Relying on the element's ID for anything isn't a great idea since it can be rewritten in JS.
*
* @return string ID for use in a form element.
*/
public function get_element_id() {
$el = $this;
$id_slugs = array();
while ( $el ) {
$slug = $el->is_proto ? 'proto' : $el->seq;
array_unshift( $id_slugs, $el->name . '-' . $slug );
$el = $el->parent;
}
return 'fm-' . implode( '-', $id_slugs );
}
/**
* Get the storage key for the form element.
*
* @return string
*/
public function get_element_key() {
$el = $this;
$key = $el->name;
// phpcs:ignore WordPress.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition -- baseline
while ( $el = $el->parent ) {
if ( $el->add_to_prefix ) {
$key = "{$el->name}_{$key}";
}
}
return $key;
}
/**
* Is this element repeatable or does it have a repeatable ancestor?
*
* @return bool True if yes, false if no.
*/
public function is_repeatable() {
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 1 != $this->limit ) {
return true;
} elseif ( $this->parent ) {
return $this->parent->is_repeatable();
}
return false;
}
/**
* Is the current field a group?
*
* @return bool True if yes, false if no.
*/
public function is_group() {
return $this instanceof \Fieldmanager_Group;
}
/**
* Presaves all elements in what could be a set of them, dispatches to $this->presave().
*
* @throws FM_Exception General FM exception.
*
* @param mixed $values The new values.
* @param mixed $current_values The current values.
* @return mixed Sanitized values.
*/
public function presave_all( $values, $current_values ) {
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 1 == $this->limit && empty( $this->multiple ) ) {
$values = $this->presave_alter_values( array( $values ), array( $current_values ) );
if ( ! empty( $values ) ) {
$value = $this->presave( $values[0], $current_values );
} else {
$value = $values;
}
if ( ! empty( $this->index ) ) {
$this->save_index( array( $value ), array( $current_values ) );
}
return $value;
}
// If $this->limit != 1, and $values is not an array, that'd just be wrong, and possibly an attack, so...
// phpcs:ignore WordPress.PHP.StrictComparisons.LooseComparison -- baseline
if ( 1 != $this->limit && ! is_array( $values ) ) {
// EXCEPT maybe this is a request to remove indices.
if ( ! empty( $this->index ) && null === $values && ! empty( $current_values ) && is_array( $current_values ) ) {
$this->save_index( null, $current_values );
return;
}
// OR doing cron, where we should just do nothing if there are no values to process.
// OR we've now accumulated some cases where a null value instead of an empty array is an acceptable case to
// just bail out instead of throwing an error. If it WAS an attack, bailing should prevent damage.
if ( null === $values || ( defined( 'DOING_CRON' ) && DOING_CRON && empty( $values ) ) ) {
return;
}
/* translators: %d: field limit */
$this->_unauthorized_access( sprintf( __( '$values should be an array because $limit is %d', 'fieldmanager' ), $this->limit ) );
}
if ( empty( $values ) ) {
$values = array();
}
// Remove the proto.
if ( isset( $values['proto'] ) ) {
unset( $values['proto'] );
}
// If $this->limit is not 0 or 1, and $values has more than $limit, that could also be an attack...
if ( $this->limit > 1 && count( $values ) > $this->limit ) {
$this->_unauthorized_access(
/* translators: 1: value count, 2: field limit */
sprintf( __( 'submitted %1$d values against a limit of %2$d', 'fieldmanager' ), count( $values ), $this->limit )
);
}
// Check for non-numeric keys.
$keys = array_keys( $values );
foreach ( $keys as $key ) {
if ( ! is_numeric( $key ) ) {
throw new FM_Exception( esc_html__( 'Use of a non-numeric key suggests that something is wrong with this group.', 'fieldmanager' ) );
}
}
// Condense the array to account for middle items removed.
$values = array_values( $values );
$values = $this->presave_alter_values( $values, $current_values );
// If this update results in fewer children, trigger presave on empty children to make up the difference.
if ( ! empty( $current_values ) && is_array( $current_values ) ) {
foreach ( array_diff( array_keys( $current_values ), array_keys( $values ) ) as $i ) {
$values[ $i ] = null;
}
}
foreach ( $values as $i => $value ) {
$values[ $i ] = $this->presave( $value, empty( $current_values[ $i ] ) ? array() : $current_values[ $i ] );
}
if ( ! $this->save_empty ) {
// Remove empty values.
$values = array_filter(
$values,
function( $value ) {
if ( is_array( $value ) ) {
return ! empty( $value );
} elseif ( null === $value ) {
return $value;
} else {
return strlen( $value );
}
}
);
// reindex the array after removing empty values.
$values = array_values( $values );
}