[JsonCodec] Use wikimedia/json-codec to implement JsonCodec
[mediawiki.git] / includes / htmlform / HTMLFormField.php
blobbc6715559a277c88b2b51a2cac20ced20f64eba3
1 <?php
3 namespace MediaWiki\HTMLForm;
5 use HtmlArmor;
6 use InvalidArgumentException;
7 use MediaWiki\Context\RequestContext;
8 use MediaWiki\Html\Html;
9 use MediaWiki\HTMLForm\Field\HTMLCheckField;
10 use MediaWiki\HTMLForm\Field\HTMLFormFieldCloner;
11 use MediaWiki\Json\FormatJson;
12 use MediaWiki\Linker\Linker;
13 use MediaWiki\Logger\LoggerFactory;
14 use MediaWiki\Message\Message;
15 use MediaWiki\Request\WebRequest;
16 use MediaWiki\Status\Status;
17 use StatusValue;
18 use Wikimedia\Message\MessageSpecifier;
20 /**
21 * The parent class to generate form fields. Any field type should
22 * be a subclass of this.
24 * @stable to extend
26 abstract class HTMLFormField {
27 /** @var array|array[] */
28 public $mParams;
30 /** @var callable(mixed,array,HTMLForm):(StatusValue|string|bool|Message) */
31 protected $mValidationCallback;
32 /** @var callable(mixed,array,HTMLForm):(StatusValue|string|bool|Message) */
33 protected $mFilterCallback;
34 /** @var string */
35 protected $mName;
36 /** @var string */
37 protected $mDir;
38 /** @var string String label, as HTML. Set on construction. */
39 protected $mLabel;
40 /** @var string */
41 protected $mID;
42 /** @var string */
43 protected $mClass = '';
44 /** @var string */
45 protected $mVFormClass = '';
46 /** @var string|false */
47 protected $mHelpClass = false;
48 /** @var mixed */
49 protected $mDefault;
50 /** @var array */
51 private $mNotices;
53 /**
54 * @var array|null|false
56 protected $mOptions = false;
57 /** @var bool */
58 protected $mOptionsLabelsNotFromMessage = false;
59 /**
60 * @var array Array to hold params for 'hide-if' or 'disable-if' statements
62 protected $mCondState = [];
63 /** @var array */
64 protected $mCondStateClass = [];
66 /**
67 * @var bool If true will generate an empty div element with no label
68 * @since 1.22
70 protected $mShowEmptyLabels = true;
72 /**
73 * @var HTMLForm|null
75 public $mParent;
77 /**
78 * This function must be implemented to return the HTML to generate
79 * the input object itself. It should not implement the surrounding
80 * table cells/rows, or labels/help messages.
82 * @param mixed $value The value to set the input to; eg a default
83 * text for a text input.
85 * @return string Valid HTML.
87 abstract public function getInputHTML( $value );
89 /**
90 * Same as getInputHTML, but returns an OOUI object.
91 * Defaults to false, which getOOUI will interpret as "use the HTML version"
92 * @stable to override
94 * @param string $value
95 * @return \OOUI\Widget|string|false
97 public function getInputOOUI( $value ) {
98 return false;
102 * Same as getInputHTML, but for Codex. This is called by CodexHTMLForm.
104 * If not overridden, falls back to getInputHTML.
106 * @param string $value The value to set the input to
107 * @param bool $hasErrors Whether there are validation errors. If set to true, this method
108 * should apply a CSS class for the error status (e.g. cdx-text-input--status-error)
109 * if the component used supports that.
110 * @return string HTML
112 public function getInputCodex( $value, $hasErrors ) {
113 // If not overridden, fall back to getInputHTML()
114 return $this->getInputHTML( $value );
118 * True if this field type is able to display errors; false if validation errors need to be
119 * displayed in the main HTMLForm error area.
120 * @stable to override
121 * @return bool
123 public function canDisplayErrors() {
124 return $this->hasVisibleOutput();
128 * Get a translated interface message
130 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
131 * and wfMessage() otherwise.
133 * Parameters are the same as wfMessage().
135 * @param string|string[]|MessageSpecifier $key
136 * @param mixed ...$params
137 * @return Message
139 public function msg( $key, ...$params ) {
140 if ( $this->mParent ) {
141 return $this->mParent->msg( $key, ...$params );
143 return wfMessage( $key, ...$params );
147 * If this field has a user-visible output or not. If not,
148 * it will not be rendered
149 * @stable to override
151 * @return bool
153 public function hasVisibleOutput() {
154 return true;
158 * Get the field name that will be used for submission.
160 * @since 1.38
161 * @return string
163 public function getName() {
164 return $this->mName;
168 * Get the closest field matching a given name.
170 * It can handle array fields like the user would expect. The general
171 * algorithm is to look for $name as a sibling of $this, then a sibling
172 * of $this's parent, and so on.
174 * @param string $name
175 * @param bool $backCompat Whether to try striping the 'wp' prefix.
176 * @return HTMLFormField
178 protected function getNearestField( $name, $backCompat = false ) {
179 // When the field is belong to a HTMLFormFieldCloner
180 $cloner = $this->mParams['cloner'] ?? null;
181 if ( $cloner instanceof HTMLFormFieldCloner ) {
182 $field = $cloner->findNearestField( $this, $name );
183 if ( $field ) {
184 return $field;
188 if ( $backCompat && str_starts_with( $name, 'wp' ) &&
189 !$this->mParent->hasField( $name )
191 // Don't break the existed use cases.
192 return $this->mParent->getField( substr( $name, 2 ) );
194 return $this->mParent->getField( $name );
198 * Fetch a field value from $alldata for the closest field matching a given
199 * name.
201 * @param array $alldata
202 * @param string $name
203 * @param bool $asDisplay Whether the reverting logic of HTMLCheckField
204 * should be ignored.
205 * @param bool $backCompat Whether to try striping the 'wp' prefix.
206 * @return mixed
208 protected function getNearestFieldValue( $alldata, $name, $asDisplay = false, $backCompat = false ) {
209 $field = $this->getNearestField( $name, $backCompat );
210 // When the field belongs to a HTMLFormFieldCloner
211 $cloner = $field->mParams['cloner'] ?? null;
212 if ( $cloner instanceof HTMLFormFieldCloner ) {
213 $value = $cloner->extractFieldData( $field, $alldata );
214 } else {
215 // Note $alldata is an empty array when first rendering a form with a formIdentifier.
216 // In that case, $alldata[$field->mParams['fieldname']] is unset and we use the
217 // field's default value
218 $value = $alldata[$field->mParams['fieldname']] ?? $field->getDefault();
221 // Check invert state for HTMLCheckField
222 if ( $asDisplay && $field instanceof HTMLCheckField && ( $field->mParams['invert'] ?? false ) ) {
223 $value = !$value;
226 return $value;
230 * Fetch a field value from $alldata for the closest field matching a given
231 * name.
233 * @deprecated since 1.38 Use getNearestFieldValue() instead.
234 * @param array $alldata
235 * @param string $name
236 * @param bool $asDisplay
237 * @return string
239 protected function getNearestFieldByName( $alldata, $name, $asDisplay = false ) {
240 return (string)$this->getNearestFieldValue( $alldata, $name, $asDisplay );
244 * Validate the cond-state params, the existence check of fields should
245 * be done later.
247 * @param array $params
249 protected function validateCondState( $params ) {
250 $origParams = $params;
251 $op = array_shift( $params );
253 $makeException = function ( string $details ) use ( $origParams ): InvalidArgumentException {
254 return new InvalidArgumentException(
255 "Invalid hide-if or disable-if specification for $this->mName: " .
256 $details . " in " . var_export( $origParams, true )
260 switch ( $op ) {
261 case 'NOT':
262 if ( count( $params ) !== 1 ) {
263 throw $makeException( "NOT takes exactly one parameter" );
265 // Fall-through intentionally
267 case 'AND':
268 case 'OR':
269 case 'NAND':
270 case 'NOR':
271 foreach ( $params as $i => $p ) {
272 if ( !is_array( $p ) ) {
273 $type = get_debug_type( $p );
274 throw $makeException( "Expected array, found $type at index $i" );
276 $this->validateCondState( $p );
278 break;
280 case '===':
281 case '!==':
282 if ( count( $params ) !== 2 ) {
283 throw $makeException( "$op takes exactly two parameters" );
285 [ $name, $value ] = $params;
286 if ( !is_string( $name ) || !is_string( $value ) ) {
287 throw $makeException( "Parameters for $op must be strings" );
289 break;
291 default:
292 throw $makeException( "Unknown operation" );
297 * Helper function for isHidden and isDisabled to handle recursive data structures.
299 * @param array $alldata
300 * @param array $params
301 * @return bool
303 protected function checkStateRecurse( array $alldata, array $params ) {
304 $op = array_shift( $params );
305 $valueChk = [ 'AND' => false, 'OR' => true, 'NAND' => false, 'NOR' => true ];
306 $valueRet = [ 'AND' => true, 'OR' => false, 'NAND' => false, 'NOR' => true ];
308 switch ( $op ) {
309 case 'AND':
310 case 'OR':
311 case 'NAND':
312 case 'NOR':
313 foreach ( $params as $p ) {
314 if ( $valueChk[$op] === $this->checkStateRecurse( $alldata, $p ) ) {
315 return !$valueRet[$op];
318 return $valueRet[$op];
320 case 'NOT':
321 return !$this->checkStateRecurse( $alldata, $params[0] );
323 case '===':
324 case '!==':
325 [ $field, $value ] = $params;
326 $testValue = (string)$this->getNearestFieldValue( $alldata, $field, true, true );
327 switch ( $op ) {
328 case '===':
329 return ( $value === $testValue );
330 case '!==':
331 return ( $value !== $testValue );
337 * Parse the cond-state array to use the field name for submission, since
338 * the key in the form descriptor is never known in HTML. Also check for
339 * field existence here.
341 * @param array $params
342 * @return mixed[]
344 protected function parseCondState( $params ) {
345 $op = array_shift( $params );
347 switch ( $op ) {
348 case 'AND':
349 case 'OR':
350 case 'NAND':
351 case 'NOR':
352 $ret = [ $op ];
353 foreach ( $params as $p ) {
354 $ret[] = $this->parseCondState( $p );
356 return $ret;
358 case 'NOT':
359 return [ 'NOT', $this->parseCondState( $params[0] ) ];
361 case '===':
362 case '!==':
363 [ $name, $value ] = $params;
364 $field = $this->getNearestField( $name, true );
365 return [ $op, $field->getName(), $value ];
370 * Parse the cond-state array for client-side.
372 * @return array[]
374 protected function parseCondStateForClient() {
375 $parsed = [];
376 foreach ( $this->mCondState as $type => $params ) {
377 $parsed[$type] = $this->parseCondState( $params );
379 return $parsed;
383 * Test whether this field is supposed to be hidden, based on the values of
384 * the other form fields.
386 * @since 1.23
387 * @param array $alldata The data collected from the form
388 * @return bool
390 public function isHidden( $alldata ) {
391 return isset( $this->mCondState['hide'] ) &&
392 $this->checkStateRecurse( $alldata, $this->mCondState['hide'] );
396 * Test whether this field is supposed to be disabled, based on the values of
397 * the other form fields.
399 * @since 1.38
400 * @param array $alldata The data collected from the form
401 * @return bool
403 public function isDisabled( $alldata ) {
404 return ( $this->mParams['disabled'] ?? false ) ||
405 $this->isHidden( $alldata ) ||
406 ( isset( $this->mCondState['disable'] )
407 && $this->checkStateRecurse( $alldata, $this->mCondState['disable'] ) );
411 * Override this function if the control can somehow trigger a form
412 * submission that shouldn't actually submit the HTMLForm.
414 * @stable to override
415 * @since 1.23
416 * @param string|array $value The value the field was submitted with
417 * @param array $alldata The data collected from the form
419 * @return bool True to cancel the submission
421 public function cancelSubmit( $value, $alldata ) {
422 return false;
426 * Override this function to add specific validation checks on the
427 * field input. Don't forget to call parent::validate() to ensure
428 * that the user-defined callback mValidationCallback is still run
429 * @stable to override
431 * @param mixed $value The value the field was submitted with
432 * @param array $alldata The data collected from the form
434 * @return bool|string|Message True on success, or String/Message error to display, or
435 * false to fail validation without displaying an error.
437 public function validate( $value, $alldata ) {
438 if ( $this->isHidden( $alldata ) ) {
439 return true;
442 if ( isset( $this->mParams['required'] )
443 && $this->mParams['required'] !== false
444 && ( $value === '' || $value === false || $value === null )
446 return $this->msg( 'htmlform-required' );
449 if ( !isset( $this->mValidationCallback ) ) {
450 return true;
453 $p = ( $this->mValidationCallback )( $value, $alldata, $this->mParent );
455 if ( $p instanceof StatusValue ) {
456 $language = $this->mParent ? $this->mParent->getLanguage() : RequestContext::getMain()->getLanguage();
458 return $p->isGood() ? true : Status::wrap( $p )->getHTML( false, false, $language );
461 return $p;
465 * @stable to override
467 * @param mixed $value
468 * @param mixed[] $alldata
470 * @return mixed
472 public function filter( $value, $alldata ) {
473 if ( isset( $this->mFilterCallback ) ) {
474 $value = ( $this->mFilterCallback )( $value, $alldata, $this->mParent );
477 return $value;
481 * Should this field have a label, or is there no input element with the
482 * appropriate id for the label to point to?
483 * @stable to override
485 * @return bool True to output a label, false to suppress
487 protected function needsLabel() {
488 return true;
492 * Tell the field whether to generate a separate label element if its label
493 * is blank.
495 * @since 1.22
497 * @param bool $show Set to false to not generate a label.
498 * @return void
500 public function setShowEmptyLabel( $show ) {
501 $this->mShowEmptyLabels = $show;
505 * Can we assume that the request is an attempt to submit a HTMLForm, as opposed to an attempt to
506 * just view it? This can't normally be distinguished for e.g. checkboxes.
508 * Returns true if the request was posted and has a field for a CSRF token (wpEditToken), or
509 * has a form identifier (wpFormIdentifier).
511 * @todo Consider moving this to HTMLForm?
512 * @param WebRequest $request
513 * @return bool
515 protected function isSubmitAttempt( WebRequest $request ) {
516 // HTMLForm would add a hidden field of edit token for forms that require to be posted.
517 return ( $request->wasPosted() && $request->getCheck( 'wpEditToken' ) )
518 // The identifier matching or not has been checked in HTMLForm::prepareForm()
519 || $request->getCheck( 'wpFormIdentifier' );
523 * Get the value that this input has been set to from a posted form,
524 * or the input's default value if it has not been set.
525 * @stable to override
527 * @param WebRequest $request
528 * @return mixed The value
530 public function loadDataFromRequest( $request ) {
531 if ( $request->getCheck( $this->mName ) ) {
532 return $request->getText( $this->mName );
533 } else {
534 return $this->getDefault();
539 * Initialise the object
541 * @stable to call
542 * @param array $params Associative Array. See HTMLForm doc for syntax.
544 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
546 public function __construct( $params ) {
547 $this->mParams = $params;
549 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm ) {
550 $this->mParent = $params['parent'];
551 } else {
552 // Normally parent is added automatically by HTMLForm::factory.
553 // Several field types already assume unconditionally this is always set,
554 // so deprecate manually creating an HTMLFormField without a parent form set.
555 wfDeprecatedMsg(
556 __METHOD__ . ": Constructing an HTMLFormField without a 'parent' parameter",
557 "1.40"
561 # Generate the label from a message, if possible
562 if ( isset( $params['label-message'] ) ) {
563 $this->mLabel = $this->getMessage( $params['label-message'] )->parse();
564 } elseif ( isset( $params['label'] ) ) {
565 if ( $params['label'] === '&#160;' || $params['label'] === "\u{00A0}" ) {
566 // Apparently some things set &nbsp directly and in an odd format
567 $this->mLabel = "\u{00A0}";
568 } else {
569 $this->mLabel = htmlspecialchars( $params['label'] );
571 } elseif ( isset( $params['label-raw'] ) ) {
572 $this->mLabel = $params['label-raw'];
575 $this->mName = $params['name'] ?? 'wp' . $params['fieldname'];
577 if ( isset( $params['dir'] ) ) {
578 $this->mDir = $params['dir'];
581 $this->mID = "mw-input-{$this->mName}";
583 if ( isset( $params['default'] ) ) {
584 $this->mDefault = $params['default'];
587 if ( isset( $params['id'] ) ) {
588 $this->mID = $params['id'];
591 if ( isset( $params['cssclass'] ) ) {
592 $this->mClass = $params['cssclass'];
595 if ( isset( $params['csshelpclass'] ) ) {
596 $this->mHelpClass = $params['csshelpclass'];
599 if ( isset( $params['validation-callback'] ) ) {
600 $this->mValidationCallback = $params['validation-callback'];
603 if ( isset( $params['filter-callback'] ) ) {
604 $this->mFilterCallback = $params['filter-callback'];
607 if ( isset( $params['hidelabel'] ) ) {
608 $this->mShowEmptyLabels = false;
610 if ( isset( $params['notices'] ) ) {
611 $this->mNotices = $params['notices'];
614 if ( isset( $params['hide-if'] ) && $params['hide-if'] ) {
615 $this->validateCondState( $params['hide-if'] );
616 $this->mCondState['hide'] = $params['hide-if'];
617 $this->mCondStateClass[] = 'mw-htmlform-hide-if';
619 if ( !( isset( $params['disabled'] ) && $params['disabled'] ) &&
620 isset( $params['disable-if'] ) && $params['disable-if']
622 $this->validateCondState( $params['disable-if'] );
623 $this->mCondState['disable'] = $params['disable-if'];
624 $this->mCondStateClass[] = 'mw-htmlform-disable-if';
629 * Get the complete table row for the input, including help text,
630 * labels, and whatever.
631 * @stable to override
633 * @param string $value The value to set the input to.
635 * @return string Complete HTML table row.
637 public function getTableRow( $value ) {
638 [ $errors, $errorClass ] = $this->getErrorsAndErrorClass( $value );
639 $inputHtml = $this->getInputHTML( $value );
640 $fieldType = $this->getClassName();
641 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
642 $cellAttributes = [];
643 $rowAttributes = [];
644 $rowClasses = '';
646 if ( !empty( $this->mParams['vertical-label'] ) ) {
647 $cellAttributes['colspan'] = 2;
648 $verticalLabel = true;
649 } else {
650 $verticalLabel = false;
653 $label = $this->getLabelHtml( $cellAttributes );
655 $field = Html::rawElement(
656 'td',
657 [ 'class' => 'mw-input' ] + $cellAttributes,
658 $inputHtml . "\n$errors"
661 if ( $this->mCondState ) {
662 $rowAttributes['data-cond-state'] = FormatJson::encode( $this->parseCondStateForClient() );
663 $rowClasses .= implode( ' ', $this->mCondStateClass );
666 if ( $verticalLabel ) {
667 $html = Html::rawElement( 'tr',
668 $rowAttributes + [ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
669 $html .= Html::rawElement( 'tr',
670 $rowAttributes + [
671 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
673 $field );
674 } else {
675 $html = Html::rawElement( 'tr',
676 $rowAttributes + [
677 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
679 $label . $field );
682 return $html . $helptext;
686 * Get the complete div for the input, including help text,
687 * labels, and whatever.
688 * @stable to override
689 * @since 1.20
691 * @param string $value The value to set the input to.
693 * @return string Complete HTML table row.
695 public function getDiv( $value ) {
696 [ $errors, $errorClass ] = $this->getErrorsAndErrorClass( $value );
697 $inputHtml = $this->getInputHTML( $value );
698 $fieldType = $this->getClassName();
699 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
700 $cellAttributes = [];
701 $label = $this->getLabelHtml( $cellAttributes );
703 $outerDivClass = [
704 'mw-input',
705 'mw-htmlform-nolabel' => ( $label === '' )
708 $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
710 if ( $horizontalLabel ) {
711 $field = "\u{00A0}" . $inputHtml . "\n$errors";
712 } else {
713 $field = Html::rawElement(
714 'div',
715 // @phan-suppress-next-line PhanUselessBinaryAddRight
716 [ 'class' => $outerDivClass ] + $cellAttributes,
717 $inputHtml . "\n$errors"
721 $wrapperAttributes = [ 'class' => [
722 "mw-htmlform-field-$fieldType",
723 $this->mClass,
724 $this->mVFormClass,
725 $errorClass,
726 ] ];
727 if ( $this->mCondState ) {
728 $wrapperAttributes['data-cond-state'] = FormatJson::encode( $this->parseCondStateForClient() );
729 $wrapperAttributes['class'] = array_merge( $wrapperAttributes['class'], $this->mCondStateClass );
731 return Html::rawElement( 'div', $wrapperAttributes, $label . $field ) .
732 $helptext;
736 * Get the OOUI version of the div. Falls back to getDiv by default.
737 * @stable to override
738 * @since 1.26
740 * @param string $value The value to set the input to.
742 * @return \OOUI\FieldLayout
744 public function getOOUI( $value ) {
745 $inputField = $this->getInputOOUI( $value );
747 if ( !$inputField ) {
748 // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
749 // generate the whole field, label and errors and all, then wrap it in a Widget.
750 // It might look weird, but it'll work OK.
751 return $this->getFieldLayoutOOUI(
752 new \OOUI\Widget( [ 'content' => new \OOUI\HtmlSnippet( $this->getDiv( $value ) ) ] ),
753 [ 'align' => 'top' ]
757 $infusable = true;
758 if ( is_string( $inputField ) ) {
759 // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
760 // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
761 // JavaScript doesn't know how to rebuilt the contents.
762 $inputField = new \OOUI\Widget( [ 'content' => new \OOUI\HtmlSnippet( $inputField ) ] );
763 $infusable = false;
766 $fieldType = $this->getClassName();
767 $help = $this->getHelpText();
768 $errors = $this->getErrorsRaw( $value );
769 foreach ( $errors as &$error ) {
770 $error = new \OOUI\HtmlSnippet( $error );
773 $config = [
774 'classes' => [ "mw-htmlform-field-$fieldType" ],
775 'align' => $this->getLabelAlignOOUI(),
776 'help' => ( $help !== null && $help !== '' ) ? new \OOUI\HtmlSnippet( $help ) : null,
777 'errors' => $errors,
778 'infusable' => $infusable,
779 'helpInline' => $this->isHelpInline(),
780 'notices' => $this->mNotices ?: [],
782 if ( $this->mClass !== '' ) {
783 $config['classes'][] = $this->mClass;
786 $preloadModules = false;
788 if ( $infusable && $this->shouldInfuseOOUI() ) {
789 $preloadModules = true;
790 $config['classes'][] = 'mw-htmlform-autoinfuse';
792 if ( $this->mCondState ) {
793 $config['classes'] = array_merge( $config['classes'], $this->mCondStateClass );
796 // the element could specify, that the label doesn't need to be added
797 $label = $this->getLabel();
798 if ( $label && $label !== "\u{00A0}" && $label !== '&#160;' ) {
799 $config['label'] = new \OOUI\HtmlSnippet( $label );
802 if ( $this->mCondState ) {
803 $preloadModules = true;
804 $config['condState'] = $this->parseCondStateForClient();
807 $config['modules'] = $this->getOOUIModules();
809 if ( $preloadModules ) {
810 $this->mParent->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
811 $this->mParent->getOutput()->addModules( $this->getOOUIModules() );
814 return $this->getFieldLayoutOOUI( $inputField, $config );
818 * Get the Codex version of the div.
819 * @since 1.42
821 * @param string $value The value to set the input to.
822 * @return string HTML
824 public function getCodex( $value ) {
825 $isDisabled = ( $this->mParams['disabled'] ?? false );
827 // Label
828 $labelDiv = '';
829 $labelValue = trim( $this->getLabel() );
830 // For weird historical reasons, a non-breaking space is treated as an empty label
831 // Check for both a literal nbsp ("\u{00A0}") and the HTML-encoded version
832 if ( $labelValue !== '' && $labelValue !== "\u{00A0}" && $labelValue !== '&#160;' ) {
833 $labelFor = $this->needsLabel() ? [ 'for' => $this->mID ] : [];
834 $labelClasses = [ 'cdx-label' ];
835 if ( $isDisabled ) {
836 $labelClasses[] = 'cdx-label--disabled';
838 // <div class="cdx-label">
839 $labelDiv = Html::rawElement( 'div', [ 'class' => $labelClasses ],
840 // <label class="cdx-label__label" for="ID">
841 Html::rawElement( 'label', [ 'class' => 'cdx-label__label' ] + $labelFor,
842 // <span class="cdx-label__label__text">
843 Html::rawElement( 'span', [ 'class' => 'cdx-label__label__text' ],
844 $labelValue
850 // Help text
851 // <div class="cdx-field__help-text">
852 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText(), [ 'cdx-field__help-text' ] );
854 // Validation message
855 // <div class="cdx-field__validation-message">
856 // $errors is a <div class="cdx-message">
857 // FIXME right now this generates a block message (cdx-message--block), we want an inline message instead
858 $validationMessage = '';
859 [ $errors, $errorClass ] = $this->getErrorsAndErrorClass( $value );
860 if ( $errors !== '' ) {
861 $validationMessage = Html::rawElement( 'div', [ 'class' => 'cdx-field__validation-message' ],
862 $errors
866 // Control
867 $inputHtml = $this->getInputCodex( $value, $errors !== '' );
868 // <div class="cdx-field__control cdx-field__control--has-help-text">
869 $controlClasses = [ 'cdx-field__control' ];
870 if ( $helptext ) {
871 $controlClasses[] = 'cdx-field__control--has-help-text';
873 $control = Html::rawElement( 'div', [ 'class' => $controlClasses ], $inputHtml );
875 // <div class="cdx-field">
876 $fieldClasses = [
877 "mw-htmlform-field-{$this->getClassName()}",
878 $this->mClass,
879 $errorClass,
880 'cdx-field'
882 if ( $isDisabled ) {
883 $fieldClasses[] = 'cdx-field--disabled';
885 $fieldAttributes = [];
886 // Set data attribute and CSS class for client side handling of hide-if / disable-if
887 if ( $this->mCondState ) {
888 $fieldAttributes['data-cond-state'] = FormatJson::encode( $this->parseCondStateForClient() );
889 $fieldClasses = array_merge( $fieldClasses, $this->mCondStateClass );
892 return Html::rawElement( 'div', [ 'class' => $fieldClasses ] + $fieldAttributes,
893 $labelDiv . $control . $helptext . $validationMessage
898 * Gets the non namespaced class name
900 * @since 1.36
902 * @return string
904 protected function getClassName() {
905 $name = explode( '\\', static::class );
906 return end( $name );
910 * Get label alignment when generating field for OOUI.
911 * @stable to override
912 * @return string 'left', 'right', 'top' or 'inline'
914 protected function getLabelAlignOOUI() {
915 return 'top';
919 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
920 * @param \OOUI\Widget $inputField
921 * @param array $config
922 * @return \OOUI\FieldLayout
924 protected function getFieldLayoutOOUI( $inputField, $config ) {
925 return new HTMLFormFieldLayout( $inputField, $config );
929 * Whether the field should be automatically infused. Note that all OOUI HTMLForm fields are
930 * infusable (you can call OO.ui.infuse() on them), but not all are infused by default, since
931 * there is no benefit in doing it e.g. for buttons and it's a small performance hit on page load.
932 * @stable to override
934 * @return bool
936 protected function shouldInfuseOOUI() {
937 // Always infuse fields with popup help text, since the interface for it is nicer with JS
938 return !$this->isHelpInline() && $this->getHelpMessages();
942 * Get the list of extra ResourceLoader modules which must be loaded client-side before it's
943 * possible to infuse this field's OOUI widget.
944 * @stable to override
946 * @return string[]
948 protected function getOOUIModules() {
949 return [];
953 * Get the complete raw fields for the input, including help text,
954 * labels, and whatever.
955 * @stable to override
956 * @since 1.20
958 * @param string $value The value to set the input to.
960 * @return string Complete HTML table row.
962 public function getRaw( $value ) {
963 [ $errors, ] = $this->getErrorsAndErrorClass( $value );
964 return "\n" . $errors .
965 $this->getLabelHtml() .
966 $this->getInputHTML( $value ) .
967 $this->getHelpTextHtmlRaw( $this->getHelpText() );
971 * Get the complete field for the input, including help text,
972 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
974 * @stable to override
975 * @since 1.25
976 * @param string $value The value to set the input to.
977 * @return string Complete HTML field.
979 public function getVForm( $value ) {
980 // Ewwww
981 $this->mVFormClass = ' mw-ui-vform-field';
982 return $this->getDiv( $value );
986 * Get the complete field as an inline element.
987 * @stable to override
988 * @since 1.25
989 * @param string $value The value to set the input to.
990 * @return string Complete HTML inline element
992 public function getInline( $value ) {
993 [ $errors, ] = $this->getErrorsAndErrorClass( $value );
994 return "\n" . $errors .
995 $this->getLabelHtml() .
996 "\u{00A0}" .
997 $this->getInputHTML( $value ) .
998 $this->getHelpTextHtmlDiv( $this->getHelpText() );
1002 * Generate help text HTML in table format
1003 * @since 1.20
1005 * @param string|null $helptext
1006 * @return string
1008 public function getHelpTextHtmlTable( $helptext ) {
1009 if ( $helptext === null ) {
1010 return '';
1013 $rowAttributes = [];
1014 if ( $this->mCondState ) {
1015 $rowAttributes['data-cond-state'] = FormatJson::encode( $this->parseCondStateForClient() );
1016 $rowAttributes['class'] = $this->mCondStateClass;
1019 $tdClasses = [ 'htmlform-tip' ];
1020 if ( $this->mHelpClass !== false ) {
1021 $tdClasses[] = $this->mHelpClass;
1023 return Html::rawElement( 'tr', $rowAttributes,
1024 Html::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext )
1029 * Generate help text HTML in div format
1030 * @since 1.20
1032 * @param string|null $helptext
1033 * @param string[] $cssClasses
1035 * @return string
1037 public function getHelpTextHtmlDiv( $helptext, $cssClasses = [] ) {
1038 if ( $helptext === null ) {
1039 return '';
1042 $wrapperAttributes = [
1043 'class' => array_merge( $cssClasses, [ 'htmlform-tip' ] ),
1045 if ( $this->mHelpClass !== false ) {
1046 $wrapperAttributes['class'][] = $this->mHelpClass;
1048 if ( $this->mCondState ) {
1049 $wrapperAttributes['data-cond-state'] = FormatJson::encode( $this->parseCondStateForClient() );
1050 $wrapperAttributes['class'] = array_merge( $wrapperAttributes['class'], $this->mCondStateClass );
1052 return Html::rawElement( 'div', $wrapperAttributes, $helptext );
1056 * Generate help text HTML formatted for raw output
1057 * @since 1.20
1059 * @param string|null $helptext
1060 * @return string
1062 public function getHelpTextHtmlRaw( $helptext ) {
1063 return $this->getHelpTextHtmlDiv( $helptext );
1066 private function getHelpMessages(): array {
1067 if ( isset( $this->mParams['help-message'] ) ) {
1068 return [ $this->mParams['help-message'] ];
1069 } elseif ( isset( $this->mParams['help-messages'] ) ) {
1070 return $this->mParams['help-messages'];
1071 } elseif ( isset( $this->mParams['help-raw'] ) ) {
1072 return [ new HtmlArmor( $this->mParams['help-raw'] ) ];
1073 } elseif ( isset( $this->mParams['help'] ) ) {
1074 // @deprecated since 1.43, use 'help-raw' key instead
1075 return [ new HtmlArmor( $this->mParams['help'] ) ];
1078 return [];
1082 * Determine the help text to display
1083 * @stable to override
1084 * @since 1.20
1085 * @return string|null HTML
1087 public function getHelpText() {
1088 $html = [];
1090 foreach ( $this->getHelpMessages() as $msg ) {
1091 if ( $msg instanceof HtmlArmor ) {
1092 $html[] = HtmlArmor::getHtml( $msg );
1093 } else {
1094 $msg = $this->getMessage( $msg );
1095 if ( $msg->exists() ) {
1096 $html[] = $msg->parse();
1101 return $html ? implode( $this->msg( 'word-separator' )->escaped(), $html ) : null;
1105 * Determine if the help text should be displayed inline.
1107 * Only applies to OOUI forms.
1109 * @since 1.31
1110 * @return bool
1112 public function isHelpInline() {
1113 return $this->mParams['help-inline'] ?? true;
1117 * Determine form errors to display and their classes
1118 * @since 1.20
1120 * phan-taint-check gets confused with returning both classes
1121 * and errors and thinks double escaping is happening, so specify
1122 * that return value has no taint.
1124 * @param string $value The value of the input
1125 * @return array [ $errors, $errorClass ]
1126 * @return-taint none
1128 public function getErrorsAndErrorClass( $value ) {
1129 $errors = $this->validate( $value, $this->mParent->mFieldData );
1131 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
1132 return [ '', '' ];
1135 return [ self::formatErrors( $errors ), 'mw-htmlform-invalid-input' ];
1139 * Determine form errors to display, returning them in an array.
1141 * @since 1.26
1142 * @param string $value The value of the input
1143 * @return string[] Array of error HTML strings
1145 public function getErrorsRaw( $value ) {
1146 $errors = $this->validate( $value, $this->mParent->mFieldData );
1148 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
1149 return [];
1152 if ( !is_array( $errors ) ) {
1153 $errors = [ $errors ];
1155 foreach ( $errors as &$error ) {
1156 if ( $error instanceof Message ) {
1157 $error = $error->parse();
1161 return $errors;
1165 * @stable to override
1166 * @return string HTML
1168 public function getLabel() {
1169 return $this->mLabel ?? '';
1173 * @stable to override
1174 * @param array $cellAttributes
1176 * @return string
1178 public function getLabelHtml( $cellAttributes = [] ) {
1179 # Don't output a for= attribute for labels with no associated input.
1180 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1181 $for = $this->needsLabel() ? [ 'for' => $this->mID ] : [];
1183 $labelValue = trim( $this->getLabel() );
1184 $hasLabel = $labelValue !== '' && $labelValue !== "\u{00A0}" && $labelValue !== '&#160;';
1186 $displayFormat = $this->mParent->getDisplayFormat();
1187 $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
1189 if ( $displayFormat === 'table' ) {
1190 return Html::rawElement( 'td',
1191 [ 'class' => 'mw-label' ] + $cellAttributes,
1192 Html::rawElement( 'label', $for, $labelValue ) );
1193 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
1194 if ( $displayFormat === 'div' && !$horizontalLabel ) {
1195 return Html::rawElement( 'div',
1196 [ 'class' => 'mw-label' ] + $cellAttributes,
1197 Html::rawElement( 'label', $for, $labelValue ) );
1198 } else {
1199 return Html::rawElement( 'label', $for, $labelValue );
1203 return '';
1207 * @stable to override
1208 * @return mixed
1210 public function getDefault() {
1211 return $this->mDefault ?? null;
1215 * Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
1217 * @return array Attributes
1219 public function getTooltipAndAccessKey() {
1220 if ( empty( $this->mParams['tooltip'] ) ) {
1221 return [];
1224 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1228 * Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
1230 * @return array Attributes
1232 public function getTooltipAndAccessKeyOOUI() {
1233 if ( empty( $this->mParams['tooltip'] ) ) {
1234 return [];
1237 return [
1238 'title' => Linker::titleAttrib( $this->mParams['tooltip'] ),
1239 'accessKey' => Linker::accesskey( $this->mParams['tooltip'] ),
1244 * Returns the given attributes from the parameters
1245 * @stable to override
1247 * @param array $list List of attributes to get
1248 * @return array Attributes
1250 public function getAttributes( array $list ) {
1251 static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1253 $ret = [];
1254 foreach ( $list as $key ) {
1255 if ( in_array( $key, $boolAttribs ) ) {
1256 if ( !empty( $this->mParams[$key] ) ) {
1257 $ret[$key] = '';
1259 } elseif ( isset( $this->mParams[$key] ) ) {
1260 $ret[$key] = $this->mParams[$key];
1264 return $ret;
1268 * Given an array of msg-key => value mappings, returns an array with keys
1269 * being the message texts. It also forces values to strings.
1271 * @param array $options
1272 * @param bool $needsParse
1273 * @return array
1274 * @return-taint tainted
1276 private function lookupOptionsKeys( $options, $needsParse ) {
1277 $ret = [];
1278 foreach ( $options as $key => $value ) {
1279 $msg = $this->msg( $key );
1280 $msgAsText = $needsParse ? $msg->parse() : $msg->plain();
1281 if ( array_key_exists( $msgAsText, $ret ) ) {
1282 LoggerFactory::getInstance( 'error' )->error(
1283 'The option that uses the message key {msg_key_one} has the same translation as ' .
1284 'another option in {lang}. This means that {msg_key_one} will not be used as an option.',
1286 'msg_key_one' => $key,
1287 'lang' => $this->mParent ?
1288 $this->mParent->getLanguageCode()->toBcp47Code() :
1289 RequestContext::getMain()->getLanguageCode()->toBcp47Code(),
1292 continue;
1294 $ret[$msgAsText] = is_array( $value )
1295 ? $this->lookupOptionsKeys( $value, $needsParse )
1296 : strval( $value );
1298 return $ret;
1302 * Recursively forces values in an array to strings, because issues arise
1303 * with integer 0 as a value.
1305 * @param array|string $array
1306 * @return array|string
1308 public static function forceToStringRecursive( $array ) {
1309 if ( is_array( $array ) ) {
1310 return array_map( [ __CLASS__, 'forceToStringRecursive' ], $array );
1311 } else {
1312 return strval( $array );
1317 * Fetch the array of options from the field's parameters. In order, this
1318 * checks 'options-messages', 'options', then 'options-message'.
1320 * @return array|null
1322 public function getOptions() {
1323 if ( $this->mOptions === false ) {
1324 if ( array_key_exists( 'options-messages', $this->mParams ) ) {
1325 $needsParse = $this->mParams['options-messages-parse'] ?? false;
1326 if ( $needsParse ) {
1327 $this->mOptionsLabelsNotFromMessage = true;
1329 $this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'], $needsParse );
1330 } elseif ( array_key_exists( 'options', $this->mParams ) ) {
1331 $this->mOptionsLabelsNotFromMessage = true;
1332 $this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
1333 } elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
1334 $message = $this->getMessage( $this->mParams['options-message'] )->inContentLanguage()->plain();
1335 $this->mOptions = Html::listDropdownOptions( $message );
1336 } else {
1337 $this->mOptions = null;
1341 return $this->mOptions;
1345 * Get options and make them into arrays suitable for OOUI.
1346 * @stable to override
1347 * @return array|null Options for inclusion in a select or whatever.
1349 public function getOptionsOOUI() {
1350 $oldoptions = $this->getOptions();
1352 if ( $oldoptions === null ) {
1353 return null;
1356 return Html::listDropdownOptionsOoui( $oldoptions );
1360 * flatten an array of options to a single array, for instance,
1361 * a set of "<options>" inside "<optgroups>".
1363 * @param array $options Associative Array with values either Strings or Arrays
1364 * @return array Flattened input
1366 public static function flattenOptions( $options ) {
1367 $flatOpts = [];
1369 foreach ( $options as $value ) {
1370 if ( is_array( $value ) ) {
1371 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1372 } else {
1373 $flatOpts[] = $value;
1377 return $flatOpts;
1381 * Formats one or more errors as accepted by field validation-callback.
1383 * @param string|Message|array $errors Array of strings or Message instances
1384 * To work around limitations in phan-taint-check the calling
1385 * class has taintedness disabled. So instead we pretend that
1386 * this method outputs html, since the result is eventually
1387 * outputted anyways without escaping and this allows us to verify
1388 * stuff is safe even though the caller has taintedness cleared.
1389 * @param-taint $errors exec_html
1390 * @return string HTML
1391 * @since 1.18
1393 protected static function formatErrors( $errors ) {
1394 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1395 $errors = array_shift( $errors );
1398 if ( is_array( $errors ) ) {
1399 foreach ( $errors as &$error ) {
1400 $error = Html::rawElement( 'li', [],
1401 $error instanceof Message ? $error->parse() : $error
1404 $errors = Html::rawElement( 'ul', [], implode( "\n", $errors ) );
1405 } elseif ( $errors instanceof Message ) {
1406 $errors = $errors->parse();
1409 return Html::errorBox( $errors );
1413 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1414 * name + parameters array) into a Message.
1415 * @param mixed $value
1416 * @return Message
1418 protected function getMessage( $value ) {
1419 $message = Message::newFromSpecifier( $value );
1421 if ( $this->mParent ) {
1422 $message->setContext( $this->mParent );
1425 return $message;
1429 * Skip this field when collecting data.
1430 * @stable to override
1431 * @param WebRequest $request
1432 * @return bool
1433 * @since 1.27
1435 public function skipLoadData( $request ) {
1436 return !empty( $this->mParams['nodata'] );
1440 * Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5
1441 * form validation to work correctly.
1443 * @return bool
1444 * @since 1.29
1446 public function needsJSForHtml5FormValidation() {
1447 // This is probably more restrictive than it needs to be, but better safe than sorry
1448 return (bool)$this->mCondState;
1452 /** @deprecated class alias since 1.42 */
1453 class_alias( HTMLFormField::class, 'HTMLFormField' );