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() {
81 $args = func_get_args();
83 if ( $this->mParent
) {
84 return $this->mParent
->msg( ...$args );
86 return wfMessage( ...$args );
90 * If this field has a user-visible output or not. If not,
91 * it will not be rendered
95 public function hasVisibleOutput() {
100 * Fetch a field value from $alldata for the closest field matching a given
103 * This is complex because it needs to handle array fields like the user
104 * would expect. The general algorithm is to look for $name as a sibling
105 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
106 * that $name itself might be referencing an array.
108 * @param array $alldata
109 * @param string $name
112 protected function getNearestFieldByName( $alldata, $name ) {
115 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
116 array_unshift( $thisKeys, $m[2] );
119 if ( substr( $tmp, 0, 2 ) == 'wp' &&
120 !array_key_exists( $tmp, $alldata ) &&
121 array_key_exists( substr( $tmp, 2 ), $alldata )
123 // Adjust for name mangling.
124 $tmp = substr( $tmp, 2 );
126 array_unshift( $thisKeys, $tmp );
130 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
131 array_unshift( $nameKeys, $m[2] );
134 array_unshift( $nameKeys, $tmp );
137 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
138 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
140 foreach ( $keys as $key ) {
141 if ( !is_array( $data ) ||
!array_key_exists( $key, $data ) ) {
146 $testValue = (string)$data;
154 * Helper function for isHidden to handle recursive data structures.
156 * @param array $alldata
157 * @param array $params
159 * @throws MWException
161 protected function isHiddenRecurse( array $alldata, array $params ) {
162 $origParams = $params;
163 $op = array_shift( $params );
168 foreach ( $params as $i => $p ) {
169 if ( !is_array( $p ) ) {
170 throw new MWException(
171 "Expected array, found " . gettype( $p ) . " at index $i"
174 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
181 foreach ( $params as $i => $p ) {
182 if ( !is_array( $p ) ) {
183 throw new MWException(
184 "Expected array, found " . gettype( $p ) . " at index $i"
187 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
194 foreach ( $params as $i => $p ) {
195 if ( !is_array( $p ) ) {
196 throw new MWException(
197 "Expected array, found " . gettype( $p ) . " at index $i"
200 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
207 foreach ( $params as $i => $p ) {
208 if ( !is_array( $p ) ) {
209 throw new MWException(
210 "Expected array, found " . gettype( $p ) . " at index $i"
213 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
220 if ( count( $params ) !== 1 ) {
221 throw new MWException( "NOT takes exactly one parameter" );
224 if ( !is_array( $p ) ) {
225 throw new MWException(
226 "Expected array, found " . gettype( $p ) . " at index 0"
229 return !$this->isHiddenRecurse( $alldata, $p );
233 if ( count( $params ) !== 2 ) {
234 throw new MWException( "$op takes exactly two parameters" );
236 list( $field, $value ) = $params;
237 if ( !is_string( $field ) ||
!is_string( $value ) ) {
238 throw new MWException( "Parameters for $op must be strings" );
240 $testValue = $this->getNearestFieldByName( $alldata, $field );
243 return ( $value === $testValue );
245 return ( $value !== $testValue );
249 throw new MWException( "Unknown operation" );
251 } catch ( Exception
$ex ) {
252 throw new MWException(
253 "Invalid hide-if specification for $this->mName: " .
254 $ex->getMessage() . " in " . var_export( $origParams, true ),
261 * Test whether this field is supposed to be hidden, based on the values of
262 * the other form fields.
265 * @param array $alldata The data collected from the form
268 public function isHidden( $alldata ) {
269 if ( !$this->mHideIf
) {
273 return $this->isHiddenRecurse( $alldata, $this->mHideIf
);
277 * Override this function if the control can somehow trigger a form
278 * submission that shouldn't actually submit the HTMLForm.
281 * @param string|array $value The value the field was submitted with
282 * @param array $alldata The data collected from the form
284 * @return bool True to cancel the submission
286 public function cancelSubmit( $value, $alldata ) {
291 * Override this function to add specific validation checks on the
292 * field input. Don't forget to call parent::validate() to ensure
293 * that the user-defined callback mValidationCallback is still run
295 * @param string|array $value The value the field was submitted with
296 * @param array $alldata The data collected from the form
298 * @return bool|string|Message True on success, or String/Message error to display, or
299 * false to fail validation without displaying an error.
301 public function validate( $value, $alldata ) {
302 if ( $this->isHidden( $alldata ) ) {
306 if ( isset( $this->mParams
['required'] )
307 && $this->mParams
['required'] !== false
310 return $this->msg( 'htmlform-required' );
313 if ( isset( $this->mValidationCallback
) ) {
314 return ( $this->mValidationCallback
)( $value, $alldata, $this->mParent
);
320 public function filter( $value, $alldata ) {
321 if ( isset( $this->mFilterCallback
) ) {
322 $value = ( $this->mFilterCallback
)( $value, $alldata, $this->mParent
);
329 * Should this field have a label, or is there no input element with the
330 * appropriate id for the label to point to?
332 * @return bool True to output a label, false to suppress
334 protected function needsLabel() {
339 * Tell the field whether to generate a separate label element if its label
344 * @param bool $show Set to false to not generate a label.
347 public function setShowEmptyLabel( $show ) {
348 $this->mShowEmptyLabels
= $show;
352 * Can we assume that the request is an attempt to submit a HTMLForm, as opposed to an attempt to
353 * just view it? This can't normally be distinguished for e.g. checkboxes.
355 * Returns true if the request has a field for a CSRF token (wpEditToken) or a form identifier
356 * (wpFormIdentifier).
358 * @param WebRequest $request
361 protected function isSubmitAttempt( WebRequest
$request ) {
362 return $request->getCheck( 'wpEditToken' ) ||
$request->getCheck( 'wpFormIdentifier' );
366 * Get the value that this input has been set to from a posted form,
367 * or the input's default value if it has not been set.
369 * @param WebRequest $request
370 * @return string The value
372 public function loadDataFromRequest( $request ) {
373 if ( $request->getCheck( $this->mName
) ) {
374 return $request->getText( $this->mName
);
376 return $this->getDefault();
381 * Initialise the object
383 * @param array $params Associative Array. See HTMLForm doc for syntax.
385 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
386 * @throws MWException
388 public function __construct( $params ) {
389 $this->mParams
= $params;
391 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm
) {
392 $this->mParent
= $params['parent'];
395 # Generate the label from a message, if possible
396 if ( isset( $params['label-message'] ) ) {
397 $this->mLabel
= $this->getMessage( $params['label-message'] )->parse();
398 } elseif ( isset( $params['label'] ) ) {
399 if ( $params['label'] === ' ' ||
$params['label'] === "\u{00A0}" ) {
400 // Apparently some things set   directly and in an odd format
401 $this->mLabel
= "\u{00A0}";
403 $this->mLabel
= htmlspecialchars( $params['label'] );
405 } elseif ( isset( $params['label-raw'] ) ) {
406 $this->mLabel
= $params['label-raw'];
409 $this->mName
= "wp{$params['fieldname']}";
410 if ( isset( $params['name'] ) ) {
411 $this->mName
= $params['name'];
414 if ( isset( $params['dir'] ) ) {
415 $this->mDir
= $params['dir'];
418 $validName = urlencode( $this->mName
);
419 $validName = str_replace( [ '%5B', '%5D' ], [ '[', ']' ], $validName );
420 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
421 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
424 $this->mID
= "mw-input-{$this->mName}";
426 if ( isset( $params['default'] ) ) {
427 $this->mDefault
= $params['default'];
430 if ( isset( $params['id'] ) ) {
432 $validId = urlencode( $id );
434 if ( $id != $validId ) {
435 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
441 if ( isset( $params['cssclass'] ) ) {
442 $this->mClass
= $params['cssclass'];
445 if ( isset( $params['csshelpclass'] ) ) {
446 $this->mHelpClass
= $params['csshelpclass'];
449 if ( isset( $params['validation-callback'] ) ) {
450 $this->mValidationCallback
= $params['validation-callback'];
453 if ( isset( $params['filter-callback'] ) ) {
454 $this->mFilterCallback
= $params['filter-callback'];
457 if ( isset( $params['hidelabel'] ) ) {
458 $this->mShowEmptyLabels
= false;
461 if ( isset( $params['hide-if'] ) ) {
462 $this->mHideIf
= $params['hide-if'];
467 * Get the complete table row for the input, including help text,
468 * labels, and whatever.
470 * @param string $value The value to set the input to.
472 * @return string Complete HTML table row.
474 public function getTableRow( $value ) {
475 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
476 $inputHtml = $this->getInputHTML( $value );
477 $fieldType = static::class;
478 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
479 $cellAttributes = [];
483 if ( !empty( $this->mParams
['vertical-label'] ) ) {
484 $cellAttributes['colspan'] = 2;
485 $verticalLabel = true;
487 $verticalLabel = false;
490 $label = $this->getLabelHtml( $cellAttributes );
492 $field = Html
::rawElement(
494 [ 'class' => 'mw-input' ] +
$cellAttributes,
495 $inputHtml . "\n$errors"
498 if ( $this->mHideIf
) {
499 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
500 $rowClasses .= ' mw-htmlform-hide-if';
503 if ( $verticalLabel ) {
504 $html = Html
::rawElement( 'tr',
505 $rowAttributes +
[ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
506 $html .= Html
::rawElement( 'tr',
508 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
513 Html
::rawElement( 'tr',
515 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
520 return $html . $helptext;
524 * Get the complete div for the input, including help text,
525 * labels, and whatever.
528 * @param string $value The value to set the input to.
530 * @return string Complete HTML table row.
532 public function getDiv( $value ) {
533 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
534 $inputHtml = $this->getInputHTML( $value );
535 $fieldType = static::class;
536 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
537 $cellAttributes = [];
538 $label = $this->getLabelHtml( $cellAttributes );
542 'mw-htmlform-nolabel' => ( $label === '' )
545 $horizontalLabel = $this->mParams
['horizontal-label'] ??
false;
547 if ( $horizontalLabel ) {
548 $field = "\u{00A0}" . $inputHtml . "\n$errors";
550 $field = Html
::rawElement(
552 [ 'class' => $outerDivClass ] +
$cellAttributes,
553 $inputHtml . "\n$errors"
556 $divCssClasses = [ "mw-htmlform-field-$fieldType",
557 $this->mClass
, $this->mVFormClass
, $errorClass ];
559 $wrapperAttributes = [
560 'class' => $divCssClasses,
562 if ( $this->mHideIf
) {
563 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
564 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
566 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
573 * Get the OOUI version of the div. Falls back to getDiv by default.
576 * @param string $value The value to set the input to.
578 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
580 public function getOOUI( $value ) {
581 $inputField = $this->getInputOOUI( $value );
583 if ( !$inputField ) {
584 // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
585 // generate the whole field, label and errors and all, then wrap it in a Widget.
586 // It might look weird, but it'll work OK.
587 return $this->getFieldLayoutOOUI(
588 new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $this->getDiv( $value ) ) ] ),
594 if ( is_string( $inputField ) ) {
595 // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
596 // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
597 // JavaScript doesn't know how to rebuilt the contents.
598 $inputField = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $inputField ) ] );
602 $fieldType = static::class;
603 $help = $this->getHelpText();
604 $errors = $this->getErrorsRaw( $value );
605 foreach ( $errors as &$error ) {
606 $error = new OOUI\
HtmlSnippet( $error );
610 'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass
],
611 'align' => $this->getLabelAlignOOUI(),
612 'help' => ( $help !== null && $help !== '' ) ?
new OOUI\
HtmlSnippet( $help ) : null,
614 'infusable' => $infusable,
615 'helpInline' => $this->isHelpInline(),
618 $preloadModules = false;
620 if ( $infusable && $this->shouldInfuseOOUI() ) {
621 $preloadModules = true;
622 $config['classes'][] = 'mw-htmlform-field-autoinfuse';
625 // the element could specify, that the label doesn't need to be added
626 $label = $this->getLabel();
627 if ( $label && $label !== "\u{00A0}" && $label !== ' ' ) {
628 $config['label'] = new OOUI\
HtmlSnippet( $label );
631 if ( $this->mHideIf
) {
632 $preloadModules = true;
633 $config['hideIf'] = $this->mHideIf
;
636 $config['modules'] = $this->getOOUIModules();
638 if ( $preloadModules ) {
639 $this->mParent
->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
640 $this->mParent
->getOutput()->addModules( $this->getOOUIModules() );
643 return $this->getFieldLayoutOOUI( $inputField, $config );
647 * Get label alignment when generating field for OOUI.
648 * @return string 'left', 'right', 'top' or 'inline'
650 protected function getLabelAlignOOUI() {
655 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
656 * @param string $inputField
657 * @param array $config
658 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
660 protected function getFieldLayoutOOUI( $inputField, $config ) {
661 if ( isset( $this->mClassWithButton
) ) {
662 $buttonWidget = $this->mClassWithButton
->getInputOOUI( '' );
663 return new HTMLFormActionFieldLayout( $inputField, $buttonWidget, $config );
665 return new HTMLFormFieldLayout( $inputField, $config );
669 * Whether the field should be automatically infused. Note that all OOUI HTMLForm fields are
670 * infusable (you can call OO.ui.infuse() on them), but not all are infused by default, since
671 * there is no benefit in doing it e.g. for buttons and it's a small performance hit on page load.
675 protected function shouldInfuseOOUI() {
676 // Always infuse fields with popup help text, since the interface for it is nicer with JS
677 return $this->getHelpText() !== null && !$this->isHelpInline();
681 * Get the list of extra ResourceLoader modules which must be loaded client-side before it's
682 * possible to infuse this field's OOUI widget.
686 protected function getOOUIModules() {
691 * Get the complete raw fields for the input, including help text,
692 * labels, and whatever.
695 * @param string $value The value to set the input to.
697 * @return string Complete HTML table row.
699 public function getRaw( $value ) {
700 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
701 $inputHtml = $this->getInputHTML( $value );
702 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
703 $cellAttributes = [];
704 $label = $this->getLabelHtml( $cellAttributes );
715 * Get the complete field for the input, including help text,
716 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
719 * @param string $value The value to set the input to.
720 * @return string Complete HTML field.
722 public function getVForm( $value ) {
724 $this->mVFormClass
= ' mw-ui-vform-field';
725 return $this->getDiv( $value );
729 * Get the complete field as an inline element.
731 * @param string $value The value to set the input to.
732 * @return string Complete HTML inline element
734 public function getInline( $value ) {
735 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
736 $inputHtml = $this->getInputHTML( $value );
737 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
738 $cellAttributes = [];
739 $label = $this->getLabelHtml( $cellAttributes );
741 $html = "\n" . $errors .
742 $label . "\u{00A0}" .
750 * Generate help text HTML in table format
753 * @param string|null $helptext
756 public function getHelpTextHtmlTable( $helptext ) {
757 if ( is_null( $helptext ) ) {
762 if ( $this->mHideIf
) {
763 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
764 $rowAttributes['class'] = 'mw-htmlform-hide-if';
767 $tdClasses = [ 'htmlform-tip' ];
768 if ( $this->mHelpClass
!== false ) {
769 $tdClasses[] = $this->mHelpClass
;
771 $row = Html
::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
772 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
778 * Generate help text HTML in div format
781 * @param string|null $helptext
785 public function getHelpTextHtmlDiv( $helptext ) {
786 if ( is_null( $helptext ) ) {
790 $wrapperAttributes = [
791 'class' => 'htmlform-tip',
793 if ( $this->mHelpClass
!== false ) {
794 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
796 if ( $this->mHideIf
) {
797 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
798 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
800 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
806 * Generate help text HTML formatted for raw output
809 * @param string|null $helptext
812 public function getHelpTextHtmlRaw( $helptext ) {
813 return $this->getHelpTextHtmlDiv( $helptext );
817 * Determine the help text to display
819 * @return string|null HTML
821 public function getHelpText() {
824 if ( isset( $this->mParams
['help-message'] ) ) {
825 $this->mParams
['help-messages'] = [ $this->mParams
['help-message'] ];
828 if ( isset( $this->mParams
['help-messages'] ) ) {
829 foreach ( $this->mParams
['help-messages'] as $msg ) {
830 $msg = $this->getMessage( $msg );
832 if ( $msg->exists() ) {
833 if ( is_null( $helptext ) ) {
836 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
838 $helptext .= $msg->parse(); // Append message
841 } elseif ( isset( $this->mParams
['help'] ) ) {
842 $helptext = $this->mParams
['help'];
849 * Determine if the help text should be displayed inline.
851 * Only applies to OOUI forms.
856 public function isHelpInline() {
857 return $this->mParams
['help-inline'] ??
true;
861 * Determine form errors to display and their classes
864 * phan-taint-check gets confused with returning both classes
865 * and errors and thinks double escaping is happening, so specify
866 * that return value has no taint.
868 * @param string $value The value of the input
869 * @return array array( $errors, $errorClass )
872 public function getErrorsAndErrorClass( $value ) {
873 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
875 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
879 $errors = self
::formatErrors( $errors );
880 $errorClass = 'mw-htmlform-invalid-input';
883 return [ $errors, $errorClass ];
887 * Determine form errors to display, returning them in an array.
890 * @param string $value The value of the input
891 * @return string[] Array of error HTML strings
893 public function getErrorsRaw( $value ) {
894 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
896 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
900 if ( !is_array( $errors ) ) {
901 $errors = [ $errors ];
903 foreach ( $errors as &$error ) {
904 if ( $error instanceof Message
) {
905 $error = $error->parse();
913 * @return string HTML
915 public function getLabel() {
916 return $this->mLabel ??
'';
919 public function getLabelHtml( $cellAttributes = [] ) {
920 # Don't output a for= attribute for labels with no associated input.
921 # Kind of hacky here, possibly we don't want these to be <label>s at all.
924 if ( $this->needsLabel() ) {
925 $for['for'] = $this->mID
;
928 $labelValue = trim( $this->getLabel() );
930 if ( $labelValue !== "\u{00A0}" && $labelValue !== ' ' && $labelValue !== '' ) {
934 $displayFormat = $this->mParent
->getDisplayFormat();
936 $horizontalLabel = $this->mParams
['horizontal-label'] ??
false;
938 if ( $displayFormat === 'table' ) {
940 Html
::rawElement( 'td',
941 [ 'class' => 'mw-label' ] +
$cellAttributes,
942 Html
::rawElement( 'label', $for, $labelValue ) );
943 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
944 if ( $displayFormat === 'div' && !$horizontalLabel ) {
946 Html
::rawElement( 'div',
947 [ 'class' => 'mw-label' ] +
$cellAttributes,
948 Html
::rawElement( 'label', $for, $labelValue ) );
950 $html = Html
::rawElement( 'label', $for, $labelValue );
957 public function getDefault() {
958 return $this->mDefault ??
null;
962 * Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
964 * @return array Attributes
966 public function getTooltipAndAccessKey() {
967 if ( empty( $this->mParams
['tooltip'] ) ) {
971 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
975 * Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
977 * @return array Attributes
979 public function getTooltipAndAccessKeyOOUI() {
980 if ( empty( $this->mParams
['tooltip'] ) ) {
985 'title' => Linker
::titleAttrib( $this->mParams
['tooltip'] ),
986 'accessKey' => Linker
::accesskey( $this->mParams
['tooltip'] ),
991 * Returns the given attributes from the parameters
993 * @param array $list List of attributes to get
994 * @return array Attributes
996 public function getAttributes( array $list ) {
997 static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1000 foreach ( $list as $key ) {
1001 if ( in_array( $key, $boolAttribs ) ) {
1002 if ( !empty( $this->mParams
[$key] ) ) {
1005 } elseif ( isset( $this->mParams
[$key] ) ) {
1006 $ret[$key] = $this->mParams
[$key];
1014 * Given an array of msg-key => value mappings, returns an array with keys
1015 * being the message texts. It also forces values to strings.
1017 * @param array $options
1020 private function lookupOptionsKeys( $options ) {
1022 foreach ( $options as $key => $value ) {
1023 $key = $this->msg( $key )->plain();
1024 $ret[$key] = is_array( $value )
1025 ?
$this->lookupOptionsKeys( $value )
1032 * Recursively forces values in an array to strings, because issues arise
1033 * with integer 0 as a value.
1035 * @param array $array
1036 * @return array|string
1038 public static function forceToStringRecursive( $array ) {
1039 if ( is_array( $array ) ) {
1040 return array_map( [ __CLASS__
, 'forceToStringRecursive' ], $array );
1042 return strval( $array );
1047 * Fetch the array of options from the field's parameters. In order, this
1048 * checks 'options-messages', 'options', then 'options-message'.
1050 * @return array|null Options array
1052 public function getOptions() {
1053 if ( $this->mOptions
=== false ) {
1054 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
1055 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
1056 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
1057 $this->mOptionsLabelsNotFromMessage
= true;
1058 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
1059 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
1060 $message = $this->getMessage( $this->mParams
['options-message'] )->inContentLanguage()->plain();
1061 $this->mOptions
= Xml
::listDropDownOptions( $message );
1063 $this->mOptions
= null;
1067 return $this->mOptions
;
1071 * Get options and make them into arrays suitable for OOUI.
1072 * @return array Options for inclusion in a select or whatever.
1074 public function getOptionsOOUI() {
1075 $oldoptions = $this->getOptions();
1077 if ( $oldoptions === null ) {
1081 return Xml
::listDropDownOptionsOoui( $oldoptions );
1085 * flatten an array of options to a single array, for instance,
1086 * a set of "<options>" inside "<optgroups>".
1088 * @param array $options Associative Array with values either Strings or Arrays
1089 * @return array Flattened input
1091 public static function flattenOptions( $options ) {
1094 foreach ( $options as $value ) {
1095 if ( is_array( $value ) ) {
1096 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1098 $flatOpts[] = $value;
1106 * Formats one or more errors as accepted by field validation-callback.
1108 * @param string|Message|array $errors Array of strings or Message instances
1109 * To work around limitations in phan-taint-check the calling
1110 * class has taintedness disabled. So instead we pretend that
1111 * this method outputs html, since the result is eventually
1112 * outputted anyways without escaping and this allows us to verify
1113 * stuff is safe even though the caller has taintedness cleared.
1114 * @param-taint $errors exec_html
1115 * @return string HTML
1118 protected static function formatErrors( $errors ) {
1119 // Note: If you change the logic in this method, change
1120 // htmlform.Checker.js to match.
1122 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1123 $errors = array_shift( $errors );
1126 if ( is_array( $errors ) ) {
1128 foreach ( $errors as $error ) {
1129 if ( $error instanceof Message
) {
1130 $lines[] = Html
::rawElement( 'li', [], $error->parse() );
1132 $lines[] = Html
::rawElement( 'li', [], $error );
1136 return Html
::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1138 if ( $errors instanceof Message
) {
1139 $errors = $errors->parse();
1142 return Html
::rawElement( 'span', [ 'class' => 'error' ], $errors );
1147 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1148 * name + parameters array) into a Message.
1149 * @param mixed $value
1152 protected function getMessage( $value ) {
1153 $message = Message
::newFromSpecifier( $value );
1155 if ( $this->mParent
) {
1156 $message->setContext( $this->mParent
);
1163 * Skip this field when collecting data.
1164 * @param WebRequest $request
1168 public function skipLoadData( $request ) {
1169 return !empty( $this->mParams
['nodata'] );
1173 * Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5
1174 * form validation to work correctly.
1179 public function needsJSForHtml5FormValidation() {
1180 if ( $this->mHideIf
) {
1181 // This is probably more restrictive than it needs to be, but better safe than sorry