4 * The parent class to generate form fields. Any field type should
5 * be a subclass of this.
7 abstract class HTMLFormField
{
8 /** @var array|array[] */
11 protected $mValidationCallback;
12 protected $mFilterCallback;
15 protected $mLabel; # String label, as HTML. Set on construction.
17 protected $mClass = '';
18 protected $mVFormClass = '';
19 protected $mHelpClass = false;
22 * @var array|bool|null
24 protected $mOptions = false;
25 protected $mOptionsLabelsNotFromMessage = false;
26 protected $mHideIf = null;
29 * @var bool If true will generate an empty div element with no label
32 protected $mShowEmptyLabels = true;
40 * This function must be implemented to return the HTML to generate
41 * the input object itself. It should not implement the surrounding
42 * table cells/rows, or labels/help messages.
44 * @param mixed $value The value to set the input to; eg a default
45 * text for a text input.
47 * @return string Valid HTML.
49 abstract public function getInputHTML( $value );
52 * Same as getInputHTML, but returns an OOUI object.
53 * Defaults to false, which getOOUI will interpret as "use the HTML version"
55 * @param string $value
56 * @return OOUI\Widget|false
58 public function getInputOOUI( $value ) {
63 * True if this field type is able to display errors; false if validation errors need to be
64 * displayed in the main HTMLForm error area.
67 public function canDisplayErrors() {
68 return $this->hasVisibleOutput();
72 * Get a translated interface message
74 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
75 * and wfMessage() otherwise.
77 * Parameters are the same as wfMessage().
81 public function msg() {
82 $args = func_get_args();
84 if ( $this->mParent
) {
85 return $this->mParent
->msg( ...$args );
87 return wfMessage( ...$args );
91 * If this field has a user-visible output or not. If not,
92 * it will not be rendered
96 public function hasVisibleOutput() {
101 * Fetch a field value from $alldata for the closest field matching a given
104 * This is complex because it needs to handle array fields like the user
105 * would expect. The general algorithm is to look for $name as a sibling
106 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
107 * that $name itself might be referencing an array.
109 * @param array $alldata
110 * @param string $name
113 protected function getNearestFieldByName( $alldata, $name ) {
116 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
117 array_unshift( $thisKeys, $m[2] );
120 if ( substr( $tmp, 0, 2 ) == 'wp' &&
121 !array_key_exists( $tmp, $alldata ) &&
122 array_key_exists( substr( $tmp, 2 ), $alldata )
124 // Adjust for name mangling.
125 $tmp = substr( $tmp, 2 );
127 array_unshift( $thisKeys, $tmp );
131 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
132 array_unshift( $nameKeys, $m[2] );
135 array_unshift( $nameKeys, $tmp );
138 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
139 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
141 foreach ( $keys as $key ) {
142 if ( !is_array( $data ) ||
!array_key_exists( $key, $data ) ) {
147 $testValue = (string)$data;
155 * Helper function for isHidden to handle recursive data structures.
157 * @param array $alldata
158 * @param array $params
160 * @throws MWException
162 protected function isHiddenRecurse( array $alldata, array $params ) {
163 $origParams = $params;
164 $op = array_shift( $params );
169 foreach ( $params as $i => $p ) {
170 if ( !is_array( $p ) ) {
171 throw new MWException(
172 "Expected array, found " . gettype( $p ) . " at index $i"
175 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
182 foreach ( $params as $i => $p ) {
183 if ( !is_array( $p ) ) {
184 throw new MWException(
185 "Expected array, found " . gettype( $p ) . " at index $i"
188 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
195 foreach ( $params as $i => $p ) {
196 if ( !is_array( $p ) ) {
197 throw new MWException(
198 "Expected array, found " . gettype( $p ) . " at index $i"
201 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
208 foreach ( $params as $i => $p ) {
209 if ( !is_array( $p ) ) {
210 throw new MWException(
211 "Expected array, found " . gettype( $p ) . " at index $i"
214 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
221 if ( count( $params ) !== 1 ) {
222 throw new MWException( "NOT takes exactly one parameter" );
225 if ( !is_array( $p ) ) {
226 throw new MWException(
227 "Expected array, found " . gettype( $p ) . " at index 0"
230 return !$this->isHiddenRecurse( $alldata, $p );
234 if ( count( $params ) !== 2 ) {
235 throw new MWException( "$op takes exactly two parameters" );
237 list( $field, $value ) = $params;
238 if ( !is_string( $field ) ||
!is_string( $value ) ) {
239 throw new MWException( "Parameters for $op must be strings" );
241 $testValue = $this->getNearestFieldByName( $alldata, $field );
244 return ( $value === $testValue );
246 return ( $value !== $testValue );
250 throw new MWException( "Unknown operation" );
252 } catch ( Exception
$ex ) {
253 throw new MWException(
254 "Invalid hide-if specification for $this->mName: " .
255 $ex->getMessage() . " in " . var_export( $origParams, true ),
262 * Test whether this field is supposed to be hidden, based on the values of
263 * the other form fields.
266 * @param array $alldata The data collected from the form
269 public function isHidden( $alldata ) {
270 if ( !$this->mHideIf
) {
274 return $this->isHiddenRecurse( $alldata, $this->mHideIf
);
278 * Override this function if the control can somehow trigger a form
279 * submission that shouldn't actually submit the HTMLForm.
282 * @param string|array $value The value the field was submitted with
283 * @param array $alldata The data collected from the form
285 * @return bool True to cancel the submission
287 public function cancelSubmit( $value, $alldata ) {
292 * Override this function to add specific validation checks on the
293 * field input. Don't forget to call parent::validate() to ensure
294 * that the user-defined callback mValidationCallback is still run
296 * @param string|array $value The value the field was submitted with
297 * @param array $alldata The data collected from the form
299 * @return bool|string|Message True on success, or String/Message error to display, or
300 * false to fail validation without displaying an error.
302 public function validate( $value, $alldata ) {
303 if ( $this->isHidden( $alldata ) ) {
307 if ( isset( $this->mParams
['required'] )
308 && $this->mParams
['required'] !== false
311 return $this->msg( 'htmlform-required' );
314 if ( isset( $this->mValidationCallback
) ) {
315 return ( $this->mValidationCallback
)( $value, $alldata, $this->mParent
);
321 public function filter( $value, $alldata ) {
322 if ( isset( $this->mFilterCallback
) ) {
323 $value = ( $this->mFilterCallback
)( $value, $alldata, $this->mParent
);
330 * Should this field have a label, or is there no input element with the
331 * appropriate id for the label to point to?
333 * @return bool True to output a label, false to suppress
335 protected function needsLabel() {
340 * Tell the field whether to generate a separate label element if its label
345 * @param bool $show Set to false to not generate a label.
348 public function setShowEmptyLabel( $show ) {
349 $this->mShowEmptyLabels
= $show;
353 * Can we assume that the request is an attempt to submit a HTMLForm, as opposed to an attempt to
354 * just view it? This can't normally be distinguished for e.g. checkboxes.
356 * Returns true if the request has a field for a CSRF token (wpEditToken) or a form identifier
357 * (wpFormIdentifier).
359 * @param WebRequest $request
362 protected function isSubmitAttempt( WebRequest
$request ) {
363 return $request->getCheck( 'wpEditToken' ) ||
$request->getCheck( 'wpFormIdentifier' );
367 * Get the value that this input has been set to from a posted form,
368 * or the input's default value if it has not been set.
370 * @param WebRequest $request
371 * @return mixed The value
373 public function loadDataFromRequest( $request ) {
374 if ( $request->getCheck( $this->mName
) ) {
375 return $request->getText( $this->mName
);
377 return $this->getDefault();
382 * Initialise the object
384 * @param array $params Associative Array. See HTMLForm doc for syntax.
386 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
387 * @throws MWException
389 public function __construct( $params ) {
390 $this->mParams
= $params;
392 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm
) {
393 $this->mParent
= $params['parent'];
396 # Generate the label from a message, if possible
397 if ( isset( $params['label-message'] ) ) {
398 $this->mLabel
= $this->getMessage( $params['label-message'] )->parse();
399 } elseif ( isset( $params['label'] ) ) {
400 if ( $params['label'] === ' ' ||
$params['label'] === "\u{00A0}" ) {
401 // Apparently some things set   directly and in an odd format
402 $this->mLabel
= "\u{00A0}";
404 $this->mLabel
= htmlspecialchars( $params['label'] );
406 } elseif ( isset( $params['label-raw'] ) ) {
407 $this->mLabel
= $params['label-raw'];
410 $this->mName
= "wp{$params['fieldname']}";
411 if ( isset( $params['name'] ) ) {
412 $this->mName
= $params['name'];
415 if ( isset( $params['dir'] ) ) {
416 $this->mDir
= $params['dir'];
419 $validName = urlencode( $this->mName
);
420 $validName = str_replace( [ '%5B', '%5D' ], [ '[', ']' ], $validName );
421 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
422 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
425 $this->mID
= "mw-input-{$this->mName}";
427 if ( isset( $params['default'] ) ) {
428 $this->mDefault
= $params['default'];
431 if ( isset( $params['id'] ) ) {
433 $validId = urlencode( $id );
435 if ( $id != $validId ) {
436 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
442 if ( isset( $params['cssclass'] ) ) {
443 $this->mClass
= $params['cssclass'];
446 if ( isset( $params['csshelpclass'] ) ) {
447 $this->mHelpClass
= $params['csshelpclass'];
450 if ( isset( $params['validation-callback'] ) ) {
451 $this->mValidationCallback
= $params['validation-callback'];
454 if ( isset( $params['filter-callback'] ) ) {
455 $this->mFilterCallback
= $params['filter-callback'];
458 if ( isset( $params['hidelabel'] ) ) {
459 $this->mShowEmptyLabels
= false;
462 if ( isset( $params['hide-if'] ) ) {
463 $this->mHideIf
= $params['hide-if'];
468 * Get the complete table row for the input, including help text,
469 * labels, and whatever.
471 * @param string $value The value to set the input to.
473 * @return string Complete HTML table row.
475 public function getTableRow( $value ) {
476 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
477 $inputHtml = $this->getInputHTML( $value );
478 $fieldType = static::class;
479 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
480 $cellAttributes = [];
484 if ( !empty( $this->mParams
['vertical-label'] ) ) {
485 $cellAttributes['colspan'] = 2;
486 $verticalLabel = true;
488 $verticalLabel = false;
491 $label = $this->getLabelHtml( $cellAttributes );
493 $field = Html
::rawElement(
495 [ 'class' => 'mw-input' ] +
$cellAttributes,
496 $inputHtml . "\n$errors"
499 if ( $this->mHideIf
) {
500 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
501 $rowClasses .= ' mw-htmlform-hide-if';
504 if ( $verticalLabel ) {
505 $html = Html
::rawElement( 'tr',
506 $rowAttributes +
[ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
507 $html .= Html
::rawElement( 'tr',
509 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
514 Html
::rawElement( 'tr',
516 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
521 return $html . $helptext;
525 * Get the complete div for the input, including help text,
526 * labels, and whatever.
529 * @param string $value The value to set the input to.
531 * @return string Complete HTML table row.
533 public function getDiv( $value ) {
534 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
535 $inputHtml = $this->getInputHTML( $value );
536 $fieldType = static::class;
537 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
538 $cellAttributes = [];
539 $label = $this->getLabelHtml( $cellAttributes );
543 'mw-htmlform-nolabel' => ( $label === '' )
546 $horizontalLabel = $this->mParams
['horizontal-label'] ??
false;
548 if ( $horizontalLabel ) {
549 $field = "\u{00A0}" . $inputHtml . "\n$errors";
551 $field = Html
::rawElement(
553 [ 'class' => $outerDivClass ] +
$cellAttributes,
554 $inputHtml . "\n$errors"
557 $divCssClasses = [ "mw-htmlform-field-$fieldType",
558 $this->mClass
, $this->mVFormClass
, $errorClass ];
560 $wrapperAttributes = [
561 'class' => $divCssClasses,
563 if ( $this->mHideIf
) {
564 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
565 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
567 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
574 * Get the OOUI version of the div. Falls back to getDiv by default.
577 * @param string $value The value to set the input to.
579 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
581 public function getOOUI( $value ) {
582 $inputField = $this->getInputOOUI( $value );
584 if ( !$inputField ) {
585 // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
586 // generate the whole field, label and errors and all, then wrap it in a Widget.
587 // It might look weird, but it'll work OK.
588 return $this->getFieldLayoutOOUI(
589 new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $this->getDiv( $value ) ) ] ),
595 if ( is_string( $inputField ) ) {
596 // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
597 // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
598 // JavaScript doesn't know how to rebuilt the contents.
599 $inputField = new OOUI\
Widget( [ 'content' => new OOUI\
HtmlSnippet( $inputField ) ] );
603 $fieldType = static::class;
604 $help = $this->getHelpText();
605 $errors = $this->getErrorsRaw( $value );
606 foreach ( $errors as &$error ) {
607 $error = new OOUI\
HtmlSnippet( $error );
611 'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass
],
612 'align' => $this->getLabelAlignOOUI(),
613 'help' => ( $help !== null && $help !== '' ) ?
new OOUI\
HtmlSnippet( $help ) : null,
615 'infusable' => $infusable,
616 'helpInline' => $this->isHelpInline(),
619 $preloadModules = false;
621 if ( $infusable && $this->shouldInfuseOOUI() ) {
622 $preloadModules = true;
623 $config['classes'][] = 'mw-htmlform-field-autoinfuse';
626 // the element could specify, that the label doesn't need to be added
627 $label = $this->getLabel();
628 if ( $label && $label !== "\u{00A0}" && $label !== ' ' ) {
629 $config['label'] = new OOUI\
HtmlSnippet( $label );
632 if ( $this->mHideIf
) {
633 $preloadModules = true;
634 $config['hideIf'] = $this->mHideIf
;
637 $config['modules'] = $this->getOOUIModules();
639 if ( $preloadModules ) {
640 $this->mParent
->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
641 $this->mParent
->getOutput()->addModules( $this->getOOUIModules() );
644 return $this->getFieldLayoutOOUI( $inputField, $config );
648 * Get label alignment when generating field for OOUI.
649 * @return string 'left', 'right', 'top' or 'inline'
651 protected function getLabelAlignOOUI() {
656 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
657 * @param OOUI\Widget $inputField
658 * @param array $config
659 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
660 * @suppress PhanUndeclaredProperty Only some subclasses declare mClassWithButton
662 protected function getFieldLayoutOOUI( $inputField, $config ) {
663 if ( isset( $this->mClassWithButton
) ) {
664 $buttonWidget = $this->mClassWithButton
->getInputOOUI( '' );
665 return new HTMLFormActionFieldLayout( $inputField, $buttonWidget, $config );
667 return new HTMLFormFieldLayout( $inputField, $config );
671 * Whether the field should be automatically infused. Note that all OOUI HTMLForm fields are
672 * infusable (you can call OO.ui.infuse() on them), but not all are infused by default, since
673 * there is no benefit in doing it e.g. for buttons and it's a small performance hit on page load.
677 protected function shouldInfuseOOUI() {
678 // Always infuse fields with popup help text, since the interface for it is nicer with JS
679 return $this->getHelpText() !== null && !$this->isHelpInline();
683 * Get the list of extra ResourceLoader modules which must be loaded client-side before it's
684 * possible to infuse this field's OOUI widget.
688 protected function getOOUIModules() {
693 * Get the complete raw fields for the input, including help text,
694 * labels, and whatever.
697 * @param string $value The value to set the input to.
699 * @return string Complete HTML table row.
701 public function getRaw( $value ) {
702 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
703 $inputHtml = $this->getInputHTML( $value );
704 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
705 $cellAttributes = [];
706 $label = $this->getLabelHtml( $cellAttributes );
717 * Get the complete field for the input, including help text,
718 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
721 * @param string $value The value to set the input to.
722 * @return string Complete HTML field.
724 public function getVForm( $value ) {
726 $this->mVFormClass
= ' mw-ui-vform-field';
727 return $this->getDiv( $value );
731 * Get the complete field as an inline element.
733 * @param string $value The value to set the input to.
734 * @return string Complete HTML inline element
736 public function getInline( $value ) {
737 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
738 $inputHtml = $this->getInputHTML( $value );
739 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
740 $cellAttributes = [];
741 $label = $this->getLabelHtml( $cellAttributes );
743 $html = "\n" . $errors .
744 $label . "\u{00A0}" .
752 * Generate help text HTML in table format
755 * @param string|null $helptext
758 public function getHelpTextHtmlTable( $helptext ) {
759 if ( is_null( $helptext ) ) {
764 if ( $this->mHideIf
) {
765 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
766 $rowAttributes['class'] = 'mw-htmlform-hide-if';
769 $tdClasses = [ 'htmlform-tip' ];
770 if ( $this->mHelpClass
!== false ) {
771 $tdClasses[] = $this->mHelpClass
;
773 $row = Html
::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
774 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
780 * Generate help text HTML in div format
783 * @param string|null $helptext
787 public function getHelpTextHtmlDiv( $helptext ) {
788 if ( is_null( $helptext ) ) {
792 $wrapperAttributes = [
793 'class' => 'htmlform-tip',
795 if ( $this->mHelpClass
!== false ) {
796 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
798 if ( $this->mHideIf
) {
799 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
800 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
802 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
808 * Generate help text HTML formatted for raw output
811 * @param string|null $helptext
814 public function getHelpTextHtmlRaw( $helptext ) {
815 return $this->getHelpTextHtmlDiv( $helptext );
819 * Determine the help text to display
821 * @return string|null HTML
823 public function getHelpText() {
826 if ( isset( $this->mParams
['help-message'] ) ) {
827 $this->mParams
['help-messages'] = [ $this->mParams
['help-message'] ];
830 if ( isset( $this->mParams
['help-messages'] ) ) {
831 foreach ( $this->mParams
['help-messages'] as $msg ) {
832 $msg = $this->getMessage( $msg );
834 if ( $msg->exists() ) {
835 if ( is_null( $helptext ) ) {
838 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
840 $helptext .= $msg->parse(); // Append message
843 } elseif ( isset( $this->mParams
['help'] ) ) {
844 $helptext = $this->mParams
['help'];
851 * Determine if the help text should be displayed inline.
853 * Only applies to OOUI forms.
858 public function isHelpInline() {
859 return $this->mParams
['help-inline'] ??
true;
863 * Determine form errors to display and their classes
866 * phan-taint-check gets confused with returning both classes
867 * and errors and thinks double escaping is happening, so specify
868 * that return value has no taint.
870 * @param string $value The value of the input
871 * @return array [ $errors, $errorClass ]
874 public function getErrorsAndErrorClass( $value ) {
875 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
877 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
881 $errors = self
::formatErrors( $errors );
882 $errorClass = 'mw-htmlform-invalid-input';
885 return [ $errors, $errorClass ];
889 * Determine form errors to display, returning them in an array.
892 * @param string $value The value of the input
893 * @return string[] Array of error HTML strings
895 public function getErrorsRaw( $value ) {
896 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
898 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
902 if ( !is_array( $errors ) ) {
903 $errors = [ $errors ];
905 foreach ( $errors as &$error ) {
906 if ( $error instanceof Message
) {
907 $error = $error->parse();
915 * @return string HTML
917 public function getLabel() {
918 return $this->mLabel ??
'';
921 public function getLabelHtml( $cellAttributes = [] ) {
922 # Don't output a for= attribute for labels with no associated input.
923 # Kind of hacky here, possibly we don't want these to be <label>s at all.
926 if ( $this->needsLabel() ) {
927 $for['for'] = $this->mID
;
930 $labelValue = trim( $this->getLabel() );
932 if ( $labelValue !== "\u{00A0}" && $labelValue !== ' ' && $labelValue !== '' ) {
936 $displayFormat = $this->mParent
->getDisplayFormat();
938 $horizontalLabel = $this->mParams
['horizontal-label'] ??
false;
940 if ( $displayFormat === 'table' ) {
942 Html
::rawElement( 'td',
943 [ 'class' => 'mw-label' ] +
$cellAttributes,
944 Html
::rawElement( 'label', $for, $labelValue ) );
945 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
946 if ( $displayFormat === 'div' && !$horizontalLabel ) {
948 Html
::rawElement( 'div',
949 [ 'class' => 'mw-label' ] +
$cellAttributes,
950 Html
::rawElement( 'label', $for, $labelValue ) );
952 $html = Html
::rawElement( 'label', $for, $labelValue );
959 public function getDefault() {
960 return $this->mDefault ??
null;
964 * Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
966 * @return array Attributes
968 public function getTooltipAndAccessKey() {
969 if ( empty( $this->mParams
['tooltip'] ) ) {
973 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
977 * Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
979 * @return array Attributes
981 public function getTooltipAndAccessKeyOOUI() {
982 if ( empty( $this->mParams
['tooltip'] ) ) {
987 'title' => Linker
::titleAttrib( $this->mParams
['tooltip'] ),
988 'accessKey' => Linker
::accesskey( $this->mParams
['tooltip'] ),
993 * Returns the given attributes from the parameters
995 * @param array $list List of attributes to get
996 * @return array Attributes
998 public function getAttributes( array $list ) {
999 static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1002 foreach ( $list as $key ) {
1003 if ( in_array( $key, $boolAttribs ) ) {
1004 if ( !empty( $this->mParams
[$key] ) ) {
1007 } elseif ( isset( $this->mParams
[$key] ) ) {
1008 $ret[$key] = $this->mParams
[$key];
1016 * Given an array of msg-key => value mappings, returns an array with keys
1017 * being the message texts. It also forces values to strings.
1019 * @param array $options
1022 private function lookupOptionsKeys( $options ) {
1024 foreach ( $options as $key => $value ) {
1025 $key = $this->msg( $key )->plain();
1026 $ret[$key] = is_array( $value )
1027 ?
$this->lookupOptionsKeys( $value )
1034 * Recursively forces values in an array to strings, because issues arise
1035 * with integer 0 as a value.
1037 * @param array|string $array
1038 * @return array|string
1040 public static function forceToStringRecursive( $array ) {
1041 if ( is_array( $array ) ) {
1042 return array_map( [ __CLASS__
, 'forceToStringRecursive' ], $array );
1044 return strval( $array );
1049 * Fetch the array of options from the field's parameters. In order, this
1050 * checks 'options-messages', 'options', then 'options-message'.
1052 * @return array|null Options array
1054 public function getOptions() {
1055 if ( $this->mOptions
=== false ) {
1056 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
1057 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
1058 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
1059 $this->mOptionsLabelsNotFromMessage
= true;
1060 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
1061 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
1062 $message = $this->getMessage( $this->mParams
['options-message'] )->inContentLanguage()->plain();
1063 $this->mOptions
= Xml
::listDropDownOptions( $message );
1065 $this->mOptions
= null;
1069 return $this->mOptions
;
1073 * Get options and make them into arrays suitable for OOUI.
1074 * @return array Options for inclusion in a select or whatever.
1076 public function getOptionsOOUI() {
1077 $oldoptions = $this->getOptions();
1079 if ( $oldoptions === null ) {
1083 return Xml
::listDropDownOptionsOoui( $oldoptions );
1087 * flatten an array of options to a single array, for instance,
1088 * a set of "<options>" inside "<optgroups>".
1090 * @param array $options Associative Array with values either Strings or Arrays
1091 * @return array Flattened input
1093 public static function flattenOptions( $options ) {
1096 foreach ( $options as $value ) {
1097 if ( is_array( $value ) ) {
1098 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
1100 $flatOpts[] = $value;
1108 * Formats one or more errors as accepted by field validation-callback.
1110 * @param string|Message|array $errors Array of strings or Message instances
1111 * To work around limitations in phan-taint-check the calling
1112 * class has taintedness disabled. So instead we pretend that
1113 * this method outputs html, since the result is eventually
1114 * outputted anyways without escaping and this allows us to verify
1115 * stuff is safe even though the caller has taintedness cleared.
1116 * @param-taint $errors exec_html
1117 * @return string HTML
1120 protected static function formatErrors( $errors ) {
1121 // Note: If you change the logic in this method, change
1122 // htmlform.Checker.js to match.
1124 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1125 $errors = array_shift( $errors );
1128 if ( is_array( $errors ) ) {
1130 foreach ( $errors as $error ) {
1131 if ( $error instanceof Message
) {
1132 $lines[] = Html
::rawElement( 'li', [], $error->parse() );
1134 $lines[] = Html
::rawElement( 'li', [], $error );
1138 return Html
::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1140 if ( $errors instanceof Message
) {
1141 $errors = $errors->parse();
1144 return Html
::rawElement( 'span', [ 'class' => 'error' ], $errors );
1149 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1150 * name + parameters array) into a Message.
1151 * @param mixed $value
1154 protected function getMessage( $value ) {
1155 $message = Message
::newFromSpecifier( $value );
1157 if ( $this->mParent
) {
1158 $message->setContext( $this->mParent
);
1165 * Skip this field when collecting data.
1166 * @param WebRequest $request
1170 public function skipLoadData( $request ) {
1171 return !empty( $this->mParams
['nodata'] );
1175 * Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5
1176 * form validation to work correctly.
1181 public function needsJSForHtml5FormValidation() {
1182 if ( $this->mHideIf
) {
1183 // This is probably more restrictive than it needs to be, but better safe than sorry