4 * The parent class to generate form fields. Any field type should
5 * be a subclass of this.
7 abstract class HTMLFormField
{
10 protected $mValidationCallback;
11 protected $mFilterCallback;
14 protected $mLabel; # String label, as HTML. Set on construction.
16 protected $mClass = '';
17 protected $mVFormClass = '';
18 protected $mHelpClass = false;
21 * @var array|bool|null
23 protected $mOptions = false;
24 protected $mOptionsLabelsNotFromMessage = false;
25 protected $mHideIf = null;
28 * @var bool If true will generate an empty div element with no label
31 protected $mShowEmptyLabels = true;
39 * This function must be implemented to return the HTML to generate
40 * the input object itself. It should not implement the surrounding
41 * table cells/rows, or labels/help messages.
43 * @param string $value The value to set the input to; eg a default
44 * text for a text input.
46 * @return string Valid HTML.
48 abstract public function getInputHTML( $value );
51 * Same as getInputHTML, but returns an OOUI object.
52 * Defaults to false, which getOOUI will interpret as "use the HTML version"
54 * @param string $value
55 * @return OOUI\Widget|false
57 public function getInputOOUI( $value ) {
62 * True if this field type is able to display errors; false if validation errors need to be
63 * displayed in the main HTMLForm error area.
66 public function canDisplayErrors() {
67 return $this->hasVisibleOutput();
71 * Get a translated interface message
73 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
74 * and wfMessage() otherwise.
76 * Parameters are the same as wfMessage().
80 public function msg( ...$args ) {
81 if ( $this->mParent
) {
82 return $this->mParent
->msg( ...$args );
84 return wfMessage( ...$args );
88 * If this field has a user-visible output or not. If not,
89 * it will not be rendered
93 public function hasVisibleOutput() {
98 * Fetch a field value from $alldata for the closest field matching a given
101 * This is complex because it needs to handle array fields like the user
102 * would expect. The general algorithm is to look for $name as a sibling
103 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
104 * that $name itself might be referencing an array.
106 * @param array $alldata
107 * @param string $name
110 protected function getNearestFieldByName( $alldata, $name ) {
113 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
114 array_unshift( $thisKeys, $m[2] );
117 if ( substr( $tmp, 0, 2 ) == 'wp' &&
118 !array_key_exists( $tmp, $alldata ) &&
119 array_key_exists( substr( $tmp, 2 ), $alldata )
121 // Adjust for name mangling.
122 $tmp = substr( $tmp, 2 );
124 array_unshift( $thisKeys, $tmp );
128 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
129 array_unshift( $nameKeys, $m[2] );
132 array_unshift( $nameKeys, $tmp );
135 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
136 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
138 foreach ( $keys as $key ) {
139 if ( !is_array( $data ) ||
!array_key_exists( $key, $data ) ) {
144 $testValue = (string)$data;
152 * Helper function for isHidden to handle recursive data structures.
154 * @param array $alldata
155 * @param array $params
157 * @throws MWException
159 protected function isHiddenRecurse( array $alldata, array $params ) {
160 $origParams = $params;
161 $op = array_shift( $params );
166 foreach ( $params as $i => $p ) {
167 if ( !is_array( $p ) ) {
168 throw new MWException(
169 "Expected array, found " . gettype( $p ) . " at index $i"
172 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
179 foreach ( $params as $i => $p ) {
180 if ( !is_array( $p ) ) {
181 throw new MWException(
182 "Expected array, found " . gettype( $p ) . " at index $i"
185 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
192 foreach ( $params as $i => $p ) {
193 if ( !is_array( $p ) ) {
194 throw new MWException(
195 "Expected array, found " . gettype( $p ) . " at index $i"
198 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
205 foreach ( $params as $i => $p ) {
206 if ( !is_array( $p ) ) {
207 throw new MWException(
208 "Expected array, found " . gettype( $p ) . " at index $i"
211 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
218 if ( count( $params ) !== 1 ) {
219 throw new MWException( "NOT takes exactly one parameter" );
222 if ( !is_array( $p ) ) {
223 throw new MWException(
224 "Expected array, found " . gettype( $p ) . " at index 0"
227 return !$this->isHiddenRecurse( $alldata, $p );
231 if ( count( $params ) !== 2 ) {
232 throw new MWException( "$op takes exactly two parameters" );
234 list( $field, $value ) = $params;
235 if ( !is_string( $field ) ||
!is_string( $value ) ) {
236 throw new MWException( "Parameters for $op must be strings" );
238 $testValue = $this->getNearestFieldByName( $alldata, $field );
241 return ( $value === $testValue );
243 return ( $value !== $testValue );
247 throw new MWException( "Unknown operation" );
249 } catch ( Exception
$ex ) {
250 throw new MWException(
251 "Invalid hide-if specification for $this->mName: " .
252 $ex->getMessage() . " in " . var_export( $origParams, true ),
259 * Test whether this field is supposed to be hidden, based on the values of
260 * the other form fields.
263 * @param array $alldata The data collected from the form
266 public function isHidden( $alldata ) {
267 if ( !$this->mHideIf
) {
271 return $this->isHiddenRecurse( $alldata, $this->mHideIf
);
275 * Override this function if the control can somehow trigger a form
276 * submission that shouldn't actually submit the HTMLForm.
279 * @param string|array $value The value the field was submitted with
280 * @param array $alldata The data collected from the form
282 * @return bool True to cancel the submission
284 public function cancelSubmit( $value, $alldata ) {
289 * Override this function to add specific validation checks on the
290 * field input. Don't forget to call parent::validate() to ensure
291 * that the user-defined callback mValidationCallback is still run
293 * @param string|array $value The value the field was submitted with
294 * @param array $alldata The data collected from the form
296 * @return bool|string|Message True on success, or String/Message error to display, or
297 * false to fail validation without displaying an error.
299 public function validate( $value, $alldata ) {
300 if ( $this->isHidden( $alldata ) ) {
304 if ( isset( $this->mParams
['required'] )
305 && $this->mParams
['required'] !== false
308 return $this->msg( 'htmlform-required' );
311 if ( isset( $this->mValidationCallback
) ) {
312 return ( $this->mValidationCallback
)( $value, $alldata, $this->mParent
);
318 public function filter( $value, $alldata ) {
319 if ( isset( $this->mFilterCallback
) ) {
320 $value = ( $this->mFilterCallback
)( $value, $alldata, $this->mParent
);
327 * Should this field have a label, or is there no input element with the
328 * appropriate id for the label to point to?
330 * @return bool True to output a label, false to suppress
332 protected function needsLabel() {
337 * Tell the field whether to generate a separate label element if its label
342 * @param bool $show Set to false to not generate a label.
345 public function setShowEmptyLabel( $show ) {
346 $this->mShowEmptyLabels
= $show;
350 * Can we assume that the request is an attempt to submit a HTMLForm, as opposed to an attempt to
351 * just view it? This can't normally be distinguished for e.g. checkboxes.
353 * Returns true if the request has a field for a CSRF token (wpEditToken) or a form identifier
354 * (wpFormIdentifier).
356 * @param WebRequest $request
359 protected function isSubmitAttempt( WebRequest
$request ) {
360 return $request->getCheck( 'wpEditToken' ) ||
$request->getCheck( 'wpFormIdentifier' );
364 * Get the value that this input has been set to from a posted form,
365 * or the input's default value if it has not been set.
367 * @param WebRequest $request
368 * @return string The value
370 public function loadDataFromRequest( $request ) {
371 if ( $request->getCheck( $this->mName
) ) {
372 return $request->getText( $this->mName
);
374 return $this->getDefault();
379 * Initialise the object
381 * @param array $params Associative Array. See HTMLForm doc for syntax.
383 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
384 * @throws MWException
386 public function __construct( $params ) {
387 $this->mParams
= $params;
389 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm
) {
390 $this->mParent
= $params['parent'];
393 # Generate the label from a message, if possible
394 if ( isset( $params['label-message'] ) ) {
395 $this->mLabel
= $this->getMessage( $params['label-message'] )->parse();
396 } elseif ( isset( $params['label'] ) ) {
397 if ( $params['label'] === ' ' ||
$params['label'] === "\u{00A0}" ) {
398 // Apparently some things set   directly and in an odd format
399 $this->mLabel
= "\u{00A0}";
401 $this->mLabel
= htmlspecialchars( $params['label'] );
403 } elseif ( isset( $params['label-raw'] ) ) {
404 $this->mLabel
= $params['label-raw'];
407 $this->mName
= "wp{$params['fieldname']}";
408 if ( isset( $params['name'] ) ) {
409 $this->mName
= $params['name'];
412 if ( isset( $params['dir'] ) ) {
413 $this->mDir
= $params['dir'];
416 $validName = urlencode( $this->mName
);
417 $validName = str_replace( [ '%5B', '%5D' ], [ '[', ']' ], $validName );
418 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
419 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
422 $this->mID
= "mw-input-{$this->mName}";
424 if ( isset( $params['default'] ) ) {
425 $this->mDefault
= $params['default'];
428 if ( isset( $params['id'] ) ) {
430 $validId = urlencode( $id );
432 if ( $id != $validId ) {
433 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
439 if ( isset( $params['cssclass'] ) ) {
440 $this->mClass
= $params['cssclass'];
443 if ( isset( $params['csshelpclass'] ) ) {
444 $this->mHelpClass
= $params['csshelpclass'];
447 if ( isset( $params['validation-callback'] ) ) {
448 $this->mValidationCallback
= $params['validation-callback'];
451 if ( isset( $params['filter-callback'] ) ) {
452 $this->mFilterCallback
= $params['filter-callback'];
455 if ( isset( $params['hidelabel'] ) ) {
456 $this->mShowEmptyLabels
= false;
459 if ( isset( $params['hide-if'] ) ) {
460 $this->mHideIf
= $params['hide-if'];
465 * Get the complete table row for the input, including help text,
466 * labels, and whatever.
468 * @param string $value The value to set the input to.
470 * @return string Complete HTML table row.
472 public function getTableRow( $value ) {
473 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
474 $inputHtml = $this->getInputHTML( $value );
475 $fieldType = static::class;
476 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
477 $cellAttributes = [];
481 if ( !empty( $this->mParams
['vertical-label'] ) ) {
482 $cellAttributes['colspan'] = 2;
483 $verticalLabel = true;
485 $verticalLabel = false;
488 $label = $this->getLabelHtml( $cellAttributes );
490 $field = Html
::rawElement(
492 [ 'class' => 'mw-input' ] +
$cellAttributes,
493 $inputHtml . "\n$errors"
496 if ( $this->mHideIf
) {
497 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
498 $rowClasses .= ' mw-htmlform-hide-if';
501 if ( $verticalLabel ) {
502 $html = Html
::rawElement( 'tr',
503 $rowAttributes +
[ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
504 $html .= Html
::rawElement( 'tr',
506 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
511 Html
::rawElement( 'tr',
513 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
518 return $html . $helptext;
522 * Get the complete div for the input, including help text,
523 * labels, and whatever.
526 * @param string $value The value to set the input to.
528 * @return string Complete HTML table row.
530 public function getDiv( $value ) {
531 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
532 $inputHtml = $this->getInputHTML( $value );
533 $fieldType = static::class;
534 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
535 $cellAttributes = [];
536 $label = $this->getLabelHtml( $cellAttributes );
540 'mw-htmlform-nolabel' => ( $label === '' )
543 $horizontalLabel = $this->mParams
['horizontal-label'] ??
false;
545 if ( $horizontalLabel ) {
546 $field = "\u{00A0}" . $inputHtml . "\n$errors";
548 $field = Html
::rawElement(
550 [ 'class' => $outerDivClass ] +
$cellAttributes,
551 $inputHtml . "\n$errors"
554 $divCssClasses = [ "mw-htmlform-field-$fieldType",
555 $this->mClass
, $this->mVFormClass
, $errorClass ];
557 $wrapperAttributes = [
558 'class' => $divCssClasses,
560 if ( $this->mHideIf
) {
561 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
562 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
564 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
571 * Get the OOUI version of the div. Falls back to getDiv by default.
574 * @param string $value The value to set the input to.
576 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
578 public function getOOUI( $value ) {
579 $inputField = $this->getInputOOUI( $value );
581 if ( !$inputField ) {
582 // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
583 // generate the whole field, label and errors and all, then wrap it in a Widget.
584 // It might look weird, but it'll work OK.
585 return $this->getFieldLayoutOOUI(
586 new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $this->getDiv( $value ) ) ] ),
592 if ( is_string( $inputField ) ) {
593 // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
594 // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
595 // JavaScript doesn't know how to rebuilt the contents.
596 $inputField = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $inputField ) ] );
600 $fieldType = static::class;
601 $help = $this->getHelpText();
602 $errors = $this->getErrorsRaw( $value );
603 foreach ( $errors as &$error ) {
604 $error = new OOUI\
HtmlSnippet( $error );
608 'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass
],
609 'align' => $this->getLabelAlignOOUI(),
610 'help' => ( $help !== null && $help !== '' ) ?
new OOUI\
HtmlSnippet( $help ) : null,
612 'infusable' => $infusable,
613 'helpInline' => $this->isHelpInline(),
616 $preloadModules = false;
618 if ( $infusable && $this->shouldInfuseOOUI() ) {
619 $preloadModules = true;
620 $config['classes'][] = 'mw-htmlform-field-autoinfuse';
623 // the element could specify, that the label doesn't need to be added
624 $label = $this->getLabel();
625 if ( $label && $label !== "\u{00A0}" && $label !== ' ' ) {
626 $config['label'] = new OOUI\
HtmlSnippet( $label );
629 if ( $this->mHideIf
) {
630 $preloadModules = true;
631 $config['hideIf'] = $this->mHideIf
;
634 $config['modules'] = $this->getOOUIModules();
636 if ( $preloadModules ) {
637 $this->mParent
->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
638 $this->mParent
->getOutput()->addModules( $this->getOOUIModules() );
641 return $this->getFieldLayoutOOUI( $inputField, $config );
645 * Get label alignment when generating field for OOUI.
646 * @return string 'left', 'right', 'top' or 'inline'
648 protected function getLabelAlignOOUI() {
653 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
654 * @param string $inputField
655 * @param array $config
656 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
658 protected function getFieldLayoutOOUI( $inputField, $config ) {
659 if ( isset( $this->mClassWithButton
) ) {
660 $buttonWidget = $this->mClassWithButton
->getInputOOUI( '' );
661 return new HTMLFormActionFieldLayout( $inputField, $buttonWidget, $config );
663 return new HTMLFormFieldLayout( $inputField, $config );
667 * Whether the field should be automatically infused. Note that all OOUI HTMLForm fields are
668 * infusable (you can call OO.ui.infuse() on them), but not all are infused by default, since
669 * there is no benefit in doing it e.g. for buttons and it's a small performance hit on page load.
673 protected function shouldInfuseOOUI() {
674 // Always infuse fields with popup help text, since the interface for it is nicer with JS
675 return $this->getHelpText() !== null && !$this->isHelpInline();
679 * Get the list of extra ResourceLoader modules which must be loaded client-side before it's
680 * possible to infuse this field's OOUI widget.
684 protected function getOOUIModules() {
689 * Get the complete raw fields for the input, including help text,
690 * labels, and whatever.
693 * @param string $value The value to set the input to.
695 * @return string Complete HTML table row.
697 public function getRaw( $value ) {
698 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
699 $inputHtml = $this->getInputHTML( $value );
700 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
701 $cellAttributes = [];
702 $label = $this->getLabelHtml( $cellAttributes );
713 * Get the complete field for the input, including help text,
714 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
717 * @param string $value The value to set the input to.
718 * @return string Complete HTML field.
720 public function getVForm( $value ) {
722 $this->mVFormClass
= ' mw-ui-vform-field';
723 return $this->getDiv( $value );
727 * Get the complete field as an inline element.
729 * @param string $value The value to set the input to.
730 * @return string Complete HTML inline element
732 public function getInline( $value ) {
733 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
734 $inputHtml = $this->getInputHTML( $value );
735 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
736 $cellAttributes = [];
737 $label = $this->getLabelHtml( $cellAttributes );
739 $html = "\n" . $errors .
740 $label . "\u{00A0}" .
748 * Generate help text HTML in table format
751 * @param string|null $helptext
754 public function getHelpTextHtmlTable( $helptext ) {
755 if ( is_null( $helptext ) ) {
760 if ( $this->mHideIf
) {
761 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
762 $rowAttributes['class'] = 'mw-htmlform-hide-if';
765 $tdClasses = [ 'htmlform-tip' ];
766 if ( $this->mHelpClass
!== false ) {
767 $tdClasses[] = $this->mHelpClass
;
769 $row = Html
::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
770 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
776 * Generate help text HTML in div format
779 * @param string|null $helptext
783 public function getHelpTextHtmlDiv( $helptext ) {
784 if ( is_null( $helptext ) ) {
788 $wrapperAttributes = [
789 'class' => 'htmlform-tip',
791 if ( $this->mHelpClass
!== false ) {
792 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
794 if ( $this->mHideIf
) {
795 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
796 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
798 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
804 * Generate help text HTML formatted for raw output
807 * @param string|null $helptext
810 public function getHelpTextHtmlRaw( $helptext ) {
811 return $this->getHelpTextHtmlDiv( $helptext );
815 * Determine the help text to display
817 * @return string|null HTML
819 public function getHelpText() {
822 if ( isset( $this->mParams
['help-message'] ) ) {
823 $this->mParams
['help-messages'] = [ $this->mParams
['help-message'] ];
826 if ( isset( $this->mParams
['help-messages'] ) ) {
827 foreach ( $this->mParams
['help-messages'] as $msg ) {
828 $msg = $this->getMessage( $msg );
830 if ( $msg->exists() ) {
831 if ( is_null( $helptext ) ) {
834 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
836 $helptext .= $msg->parse(); // Append message
839 } elseif ( isset( $this->mParams
['help'] ) ) {
840 $helptext = $this->mParams
['help'];
847 * Determine if the help text should be displayed inline.
849 * Only applies to OOUI forms.
854 public function isHelpInline() {
855 return $this->mParams
['help-inline'] ??
true;
859 * Determine form errors to display and their classes
862 * phan-taint-check gets confused with returning both classes
863 * and errors and thinks double escaping is happening, so specify
864 * that return value has no taint.
866 * @param string $value The value of the input
867 * @return array array( $errors, $errorClass )
870 public function getErrorsAndErrorClass( $value ) {
871 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
873 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
877 $errors = self
::formatErrors( $errors );
878 $errorClass = 'mw-htmlform-invalid-input';
881 return [ $errors, $errorClass ];
885 * Determine form errors to display, returning them in an array.
888 * @param string $value The value of the input
889 * @return string[] Array of error HTML strings
891 public function getErrorsRaw( $value ) {
892 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
894 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
898 if ( !is_array( $errors ) ) {
899 $errors = [ $errors ];
901 foreach ( $errors as &$error ) {
902 if ( $error instanceof Message
) {
903 $error = $error->parse();
911 * @return string HTML
913 public function getLabel() {
914 return $this->mLabel ??
'';
917 public function getLabelHtml( $cellAttributes = [] ) {
918 # Don't output a for= attribute for labels with no associated input.
919 # Kind of hacky here, possibly we don't want these to be <label>s at all.
922 if ( $this->needsLabel() ) {
923 $for['for'] = $this->mID
;
926 $labelValue = trim( $this->getLabel() );
928 if ( $labelValue !== "\u{00A0}" && $labelValue !== ' ' && $labelValue !== '' ) {
932 $displayFormat = $this->mParent
->getDisplayFormat();
934 $horizontalLabel = $this->mParams
['horizontal-label'] ??
false;
936 if ( $displayFormat === 'table' ) {
938 Html
::rawElement( 'td',
939 [ 'class' => 'mw-label' ] +
$cellAttributes,
940 Html
::rawElement( 'label', $for, $labelValue ) );
941 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
942 if ( $displayFormat === 'div' && !$horizontalLabel ) {
944 Html
::rawElement( 'div',
945 [ 'class' => 'mw-label' ] +
$cellAttributes,
946 Html
::rawElement( 'label', $for, $labelValue ) );
948 $html = Html
::rawElement( 'label', $for, $labelValue );
955 public function getDefault() {
956 return $this->mDefault ??
null;
960 * Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
962 * @return array Attributes
964 public function getTooltipAndAccessKey() {
965 if ( empty( $this->mParams
['tooltip'] ) ) {
969 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
973 * Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
975 * @return array Attributes
977 public function getTooltipAndAccessKeyOOUI() {
978 if ( empty( $this->mParams
['tooltip'] ) ) {
983 'title' => Linker
::titleAttrib( $this->mParams
['tooltip'] ),
984 'accessKey' => Linker
::accesskey( $this->mParams
['tooltip'] ),
989 * Returns the given attributes from the parameters
991 * @param array $list List of attributes to get
992 * @return array Attributes
994 public function getAttributes( array $list ) {
995 static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
998 foreach ( $list as $key ) {
999 if ( in_array( $key, $boolAttribs ) ) {
1000 if ( !empty( $this->mParams
[$key] ) ) {
1003 } elseif ( isset( $this->mParams
[$key] ) ) {
1004 $ret[$key] = $this->mParams
[$key];
1012 * Given an array of msg-key => value mappings, returns an array with keys
1013 * being the message texts. It also forces values to strings.
1015 * @param array $options
1018 private function lookupOptionsKeys( $options ) {
1020 foreach ( $options as $key => $value ) {
1021 $key = $this->msg( $key )->plain();
1022 $ret[$key] = is_array( $value )
1023 ?
$this->lookupOptionsKeys( $value )
1030 * Recursively forces values in an array to strings, because issues arise
1031 * with integer 0 as a value.
1033 * @param array $array
1034 * @return array|string
1036 public static function forceToStringRecursive( $array ) {
1037 if ( is_array( $array ) ) {
1038 return array_map( [ __CLASS__
, 'forceToStringRecursive' ], $array );
1040 return strval( $array );
1045 * Fetch the array of options from the field's parameters. In order, this
1046 * checks 'options-messages', 'options', then 'options-message'.
1048 * @return array|null Options array
1050 public function getOptions() {
1051 if ( $this->mOptions
=== false ) {
1052 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
1053 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
1054 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
1055 $this->mOptionsLabelsNotFromMessage
= true;
1056 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
1057 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
1058 $message = $this->getMessage( $this->mParams
['options-message'] )->inContentLanguage()->plain();
1059 $this->mOptions
= Xml
::listDropDownOptions( $message );
1061 $this->mOptions
= null;
1065 return $this->mOptions
;
1069 * Get options and make them into arrays suitable for OOUI.
1070 * @return array Options for inclusion in a select or whatever.
1072 public function getOptionsOOUI() {
1073 $oldoptions = $this->getOptions();
1075 if ( $oldoptions === null ) {
1079 return Xml
::listDropDownOptionsOoui( $oldoptions );
1083 * flatten an array of options to a single array, for instance,
1084 * a set of "<options>" inside "<optgroups>".
1086 * @param array $options Associative Array with values either Strings or Arrays
1087 * @return array Flattened input
1089 public static function flattenOptions( $options ) {
1092 foreach ( $options as $value ) {
1093 if ( is_array( $value ) ) {
1094 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1096 $flatOpts[] = $value;
1104 * Formats one or more errors as accepted by field validation-callback.
1106 * @param string|Message|array $errors Array of strings or Message instances
1107 * To work around limitations in phan-taint-check the calling
1108 * class has taintedness disabled. So instead we pretend that
1109 * this method outputs html, since the result is eventually
1110 * outputted anyways without escaping and this allows us to verify
1111 * stuff is safe even though the caller has taintedness cleared.
1112 * @param-taint $errors exec_html
1113 * @return string HTML
1116 protected static function formatErrors( $errors ) {
1117 // Note: If you change the logic in this method, change
1118 // htmlform.Checker.js to match.
1120 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1121 $errors = array_shift( $errors );
1124 if ( is_array( $errors ) ) {
1126 foreach ( $errors as $error ) {
1127 if ( $error instanceof Message
) {
1128 $lines[] = Html
::rawElement( 'li', [], $error->parse() );
1130 $lines[] = Html
::rawElement( 'li', [], $error );
1134 return Html
::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1136 if ( $errors instanceof Message
) {
1137 $errors = $errors->parse();
1140 return Html
::rawElement( 'span', [ 'class' => 'error' ], $errors );
1145 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1146 * name + parameters array) into a Message.
1147 * @param mixed $value
1150 protected function getMessage( $value ) {
1151 $message = Message
::newFromSpecifier( $value );
1153 if ( $this->mParent
) {
1154 $message->setContext( $this->mParent
);
1161 * Skip this field when collecting data.
1162 * @param WebRequest $request
1166 public function skipLoadData( $request ) {
1167 return !empty( $this->mParams
['nodata'] );
1171 * Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5
1172 * form validation to work correctly.
1177 public function needsJSForHtml5FormValidation() {
1178 if ( $this->mHideIf
) {
1179 // This is probably more restrictive than it needs to be, but better safe than sorry