Debian Codegraph @

includes/htmlform/HTMLFormField.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\HTMLForm;
4
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;
19
20 /**
21 * The parent class to generate form fields. Any field type should
22 * be a subclass of this.
23 *
24 * @stable to extend
25 */
26 abstract class HTMLFormField {
27 /** @var array|array[] */
28 public $mParams;
29
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;
52
53 /**
54 * @var array|null|false
55 */
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
61 */
62 protected $mCondState = [];
63 /** @var array */
64 protected $mCondStateClass = [];
65
66 /**
67 * @var bool If true will generate an empty div element with no label
68 * @since 1.22
69 */
70 protected $mShowEmptyLabels = true;
71
72 /**
73 * @var HTMLForm|null
74 */
75 public $mParent;
76
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.
81 *
82 * @param mixed $value The value to set the input to; eg a default
83 * text for a text input.
84 *
85 * @return string Valid HTML.
86 */
87 abstract public function getInputHTML( $value );
88
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
93 *
94 * @param string $value
95 * @return \OOUI\Widget|string|false
96 */
97 public function getInputOOUI( $value ) {
98 return false;
99 }
100
101 /**
102 * Same as getInputHTML, but for Codex. This is called by CodexHTMLForm.
103 *
104 * If not overridden, falls back to getInputHTML.
105 *
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
111 */
112 public function getInputCodex( $value, $hasErrors ) {
113 // If not overridden, fall back to getInputHTML()
114 return $this->getInputHTML( $value );
115 }
116
117 /**
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
122 */
123 public function canDisplayErrors() {
124 return $this->hasVisibleOutput();
125 }
126
127 /**
128 * Get a translated interface message
129 *
130 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
131 * and wfMessage() otherwise.
132 *
133 * Parameters are the same as wfMessage().
134 *
135 * @param string|string[]|MessageSpecifier $key
136 * @param mixed ...$params
137 * @return Message
138 */
139 public function msg( $key, ...$params ) {
140 if ( $this->mParent ) {
141 return $this->mParent->msg( $key, ...$params );
142 }
143 return wfMessage( $key, ...$params );
144 }
145
146 /**
147 * If this field has a user-visible output or not. If not,
148 * it will not be rendered
149 * @stable to override
150 *
151 * @return bool
152 */
153 public function hasVisibleOutput() {
154 return true;
155 }
156
157 /**
158 * Get the field name that will be used for submission.
159 *
160 * @since 1.38
161 * @return string
162 */
163 public function getName() {
164 return $this->mName;
165 }
166
167 /**
168 * Get the closest field matching a given name.
169 *
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.
173 *
174 * @param string $name
175 * @param bool $backCompat Whether to try striping the 'wp' prefix.
176 * @return HTMLFormField
177 */
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;
185 }
186 }
187
188 if ( $backCompat && str_starts_with( $name, 'wp' ) &&
189 !$this->mParent->hasField( $name )
190 ) {
191 // Don't break the existed use cases.
192 return $this->mParent->getField( substr( $name, 2 ) );
193 }
194 return $this->mParent->getField( $name );
195 }
196
197 /**
198 * Fetch a field value from $alldata for the closest field matching a given
199 * name.
200 *
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
207 */
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();
219 }
220
221 // Check invert state for HTMLCheckField
222 if ( $asDisplay && $field instanceof HTMLCheckField && ( $field->mParams['invert'] ?? false ) ) {
223 $value = !$value;
224 }
225
226 return $value;
227 }
228
229 /**
230 * Fetch a field value from $alldata for the closest field matching a given
231 * name.
232 *
233 * @deprecated since 1.38 Use getNearestFieldValue() instead.
234 * @param array $alldata
235 * @param string $name
236 * @param bool $asDisplay
237 * @return string
238 */
239 protected function getNearestFieldByName( $alldata, $name, $asDisplay = false ) {
240 return (string)$this->getNearestFieldValue( $alldata, $name, $asDisplay );
241 }
242
243 /**
244 * Validate the cond-state params, the existence check of fields should
245 * be done later.
246 *
247 * @param array $params
248 */
249 protected function validateCondState( $params ) {
250 $origParams = $params;
251 $op = array_shift( $params );
252
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 )
257 );
258 };
259
260 switch ( $op ) {
261 case 'NOT':
262 if ( count( $params ) !== 1 ) {
263 throw $makeException( "NOT takes exactly one parameter" );
264 }
265 // Fall-through intentionally
266
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" );
275 }
276 $this->validateCondState( $p );
277 }
278 break;
279
280 case '===':
281 case '!==':
282 if ( count( $params ) !== 2 ) {
283 throw $makeException( "$op takes exactly two parameters" );
284 }
285 [ $name, $value ] = $params;
286 if ( !is_string( $name ) || !is_string( $value ) ) {
287 throw $makeException( "Parameters for $op must be strings" );
288 }
289 break;
290
291 default:
292 throw $makeException( "Unknown operation" );
293 }
294 }
295
296 /**
297 * Helper function for isHidden and isDisabled to handle recursive data structures.
298 *
299 * @param array $alldata
300 * @param array $params
301 * @return bool
302 */
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 ];
307
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];
316 }
317 }
318 return $valueRet[$op];
319
320 case 'NOT':
321 return !$this->checkStateRecurse( $alldata, $params[0] );
322
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 );
332 }
333 }
334 }
335
336 /**
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.
340 *
341 * @param array $params
342 * @return mixed[]
343 */
344 protected function parseCondState( $params ) {
345 $op = array_shift( $params );
346
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 );
355 }
356 return $ret;
357
358 case 'NOT':
359 return [ 'NOT', $this->parseCondState( $params[0] ) ];
360
361 case '===':
362 case '!==':
363 [ $name, $value ] = $params;
364 $field = $this->getNearestField( $name, true );
365 return [ $op, $field->getName(), $value ];
366 }
367 }
368
369 /**
370 * Parse the cond-state array for client-side.
371 *
372 * @return array[]
373 */
374 protected function parseCondStateForClient() {
375 $parsed = [];
376 foreach ( $this->mCondState as $type => $params ) {
377 $parsed[$type] = $this->parseCondState( $params );
378 }
379 return $parsed;
380 }
381
382 /**
383 * Test whether this field is supposed to be hidden, based on the values of
384 * the other form fields.
385 *
386 * @since 1.23
387 * @param array $alldata The data collected from the form
388 * @return bool
389 */
390 public function isHidden( $alldata ) {
391 return isset( $this->mCondState['hide'] ) &&
392 $this->checkStateRecurse( $alldata, $this->mCondState['hide'] );
393 }
394
395 /**
396 * Test whether this field is supposed to be disabled, based on the values of
397 * the other form fields.
398 *
399 * @since 1.38
400 * @param array $alldata The data collected from the form
401 * @return bool
402 */
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'] ) );
408 }
409
410 /**
411 * Override this function if the control can somehow trigger a form
412 * submission that shouldn't actually submit the HTMLForm.
413 *
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
418 *
419 * @return bool True to cancel the submission
420 */
421 public function cancelSubmit( $value, $alldata ) {
422 return false;
423 }
424
425 /**
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
430 *
431 * @param mixed $value The value the field was submitted with
432 * @param array $alldata The data collected from the form
433 *
434 * @return bool|string|Message True on success, or String/Message error to display, or
435 * false to fail validation without displaying an error.
436 */
437 public function validate( $value, $alldata ) {
438 if ( $this->isHidden( $alldata ) ) {
439 return true;
440 }
441
442 if ( isset( $this->mParams['required'] )
443 && $this->mParams['required'] !== false
444 && ( $value === '' || $value === false || $value === null )
445 ) {
446 return $this->msg( 'htmlform-required' );
447 }
448
449 if ( !isset( $this->mValidationCallback ) ) {
450 return true;
451 }
452
453 $p = ( $this->mValidationCallback )( $value, $alldata, $this->mParent );
454
455 if ( $p instanceof StatusValue ) {
456 $language = $this->mParent ? $this->mParent->getLanguage() : RequestContext::getMain()->getLanguage();
457
458 return $p->isGood() ? true : Status::wrap( $p )->getHTML( false, false, $language );
459 }
460
461 return $p;
462 }
463
464 /**
465 * @stable to override
466 *
467 * @param mixed $value
468 * @param mixed[] $alldata
469 *
470 * @return mixed
471 */
472 public function filter( $value, $alldata ) {
473 if ( isset( $this->mFilterCallback ) ) {
474 $value = ( $this->mFilterCallback )( $value, $alldata, $this->mParent );
475 }
476
477 return $value;
478 }
479
480 /**
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
484 *
485 * @return bool True to output a label, false to suppress
486 */
487 protected function needsLabel() {
488 return true;
489 }
490
491 /**
492 * Tell the field whether to generate a separate label element if its label
493 * is blank.
494 *
495 * @since 1.22
496 *
497 * @param bool $show Set to false to not generate a label.
498 * @return void
499 */
500 public function setShowEmptyLabel( $show ) {
501 $this->mShowEmptyLabels = $show;
502 }
503
504 /**
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.
507 *
508 * Returns true if the request was posted and has a field for a CSRF token (wpEditToken), or
509 * has a form identifier (wpFormIdentifier).
510 *
511 * @todo Consider moving this to HTMLForm?
512 * @param WebRequest $request
513 * @return bool
514 */
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' );
520 }
521
522 /**
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
526 *
527 * @param WebRequest $request
528 * @return mixed The value
529 */
530 public function loadDataFromRequest( $request ) {
531 if ( $request->getCheck( $this->mName ) ) {
532 return $request->getText( $this->mName );
533 } else {
534 return $this->getDefault();
535 }
536 }
537
538 /**
539 * Initialise the object
540 *
541 * @stable to call
542 * @param array $params Associative Array. See HTMLForm doc for syntax.
543 *
544 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
545 */
546 public function __construct( $params ) {
547 $this->mParams = $params;
548
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"
558 );
559 }
560
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'] );
570 }
571 } elseif ( isset( $params['label-raw'] ) ) {
572 $this->mLabel = $params['label-raw'];
573 }
574
575 $this->mName = $params['name'] ?? 'wp' . $params['fieldname'];
576
577 if ( isset( $params['dir'] ) ) {
578 $this->mDir = $params['dir'];
579 }
580
581 $this->mID = "mw-input-{$this->mName}";
582
583 if ( isset( $params['default'] ) ) {
584 $this->mDefault = $params['default'];
585 }
586
587 if ( isset( $params['id'] ) ) {
588 $this->mID = $params['id'];
589 }
590
591 if ( isset( $params['cssclass'] ) ) {
592 $this->mClass = $params['cssclass'];
593 }
594
595 if ( isset( $params['csshelpclass'] ) ) {
596 $this->mHelpClass = $params['csshelpclass'];
597 }
598
599 if ( isset( $params['validation-callback'] ) ) {
600 $this->mValidationCallback = $params['validation-callback'];
601 }
602
603 if ( isset( $params['filter-callback'] ) ) {
604 $this->mFilterCallback = $params['filter-callback'];
605 }
606
607 if ( isset( $params['hidelabel'] ) ) {
608 $this->mShowEmptyLabels = false;
609 }
610 if ( isset( $params['notices'] ) ) {
611 $this->mNotices = $params['notices'];
612 }
613
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';
618 }
619 if ( !( isset( $params['disabled'] ) && $params['disabled'] ) &&
620 isset( $params['disable-if'] ) && $params['disable-if']
621 ) {
622 $this->validateCondState( $params['disable-if'] );
623 $this->mCondState['disable'] = $params['disable-if'];
624 $this->mCondStateClass[] = 'mw-htmlform-disable-if';
625 }
626 }
627
628 /**
629 * Get the complete table row for the input, including help text,
630 * labels, and whatever.
631 * @stable to override
632 *
633 * @param string $value The value to set the input to.
634 *
635 * @return string Complete HTML table row.
636 */
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 = '';
645
646 if ( !empty( $this->mParams['vertical-label'] ) ) {
647 $cellAttributes['colspan'] = 2;
648 $verticalLabel = true;
649 } else {
650 $verticalLabel = false;
651 }
652
653 $label = $this->getLabelHtml( $cellAttributes );
654
655 $field = Html::rawElement(
656 'td',
657 [ 'class' => 'mw-input' ] + $cellAttributes,
658 $inputHtml . "\n$errors"
659 );
660
661 if ( $this->mCondState ) {
662 $rowAttributes['data-cond-state'] = FormatJson::encode( $this->parseCondStateForClient() );
663 $rowClasses .= implode( ' ', $this->mCondStateClass );
664 }
665
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"
672 ],
673 $field );
674 } else {
675 $html = Html::rawElement( 'tr',
676 $rowAttributes + [
677 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
678 ],
679 $label . $field );
680 }
681
682 return $html . $helptext;
683 }
684
685 /**
686 * Get the complete div for the input, including help text,
687 * labels, and whatever.
688 * @stable to override
689 * @since 1.20
690 *
691 * @param string $value The value to set the input to.
692 *
693 * @return string Complete HTML table row.
694 */
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 );
702
703 $outerDivClass = [
704 'mw-input',
705 'mw-htmlform-nolabel' => ( $label === '' )
706 ];
707
708 $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
709
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"
718 );
719 }
720
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 );
730 }
731 return Html::rawElement( 'div', $wrapperAttributes, $label . $field ) .
732 $helptext;
733 }
734
735 /**
736 * Get the OOUI version of the div. Falls back to getDiv by default.
737 * @stable to override
738 * @since 1.26
739 *
740 * @param string $value The value to set the input to.
741 *
742 * @return \OOUI\FieldLayout
743 */
744 public function getOOUI( $value ) {
745 $inputField = $this->getInputOOUI( $value );
746
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' ]
754 );
755 }
756
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;
764 }
765
766 $fieldType = $this->getClassName();
767 $help = $this->getHelpText();
768 $errors = $this->getErrorsRaw( $value );
769 foreach ( $errors as &$error ) {
770 $error = new \OOUI\HtmlSnippet( $error );
771 }
772
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 ?: [],
781 ];
782 if ( $this->mClass !== '' ) {
783 $config['classes'][] = $this->mClass;
784 }
785
786 $preloadModules = false;
787
788 if ( $infusable && $this->shouldInfuseOOUI() ) {
789 $preloadModules = true;
790 $config['classes'][] = 'mw-htmlform-autoinfuse';
791 }
792 if ( $this->mCondState ) {
793 $config['classes'] = array_merge( $config['classes'], $this->mCondStateClass );
794 }
795
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 );
800 }
801
802 if ( $this->mCondState ) {
803 $preloadModules = true;
804 $config['condState'] = $this->parseCondStateForClient();
805 }
806
807 $config['modules'] = $this->getOOUIModules();
808
809 if ( $preloadModules ) {
810 $this->mParent->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
811 $this->mParent->getOutput()->addModules( $this->getOOUIModules() );
812 }
813
814 return $this->getFieldLayoutOOUI( $inputField, $config );
815 }
816
817 /**
818 * Get the Codex version of the div.
819 * @since 1.42
820 *
821 * @param string $value The value to set the input to.
822 * @return string HTML
823 */
824 public function getCodex( $value ) {
825 $isDisabled = ( $this->mParams['disabled'] ?? false );
826
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';
837 }
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
845 )
846 )
847 );
848 }
849
850 // Help text
851 // <div class="cdx-field__help-text">
852 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText(), [ 'cdx-field__help-text' ] );
853
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
863 );
864 }
865
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';
872 }
873 $control = Html::rawElement( 'div', [ 'class' => $controlClasses ], $inputHtml );
874
875 // <div class="cdx-field">
876 $fieldClasses = [
877 "mw-htmlform-field-{$this->getClassName()}",
878 $this->mClass,
879 $errorClass,
880 'cdx-field'
881 ];
882 if ( $isDisabled ) {
883 $fieldClasses[] = 'cdx-field--disabled';
884 }
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 );
890 }
891
892 return Html::rawElement( 'div', [ 'class' => $fieldClasses ] + $fieldAttributes,
893 $labelDiv . $control . $helptext . $validationMessage
894 );
895 }
896
897 /**
898 * Gets the non namespaced class name
899 *
900 * @since 1.36
901 *
902 * @return string
903 */
904 protected function getClassName() {
905 $name = explode( '\\', static::class );
906 return end( $name );
907 }
908
909 /**
910 * Get label alignment when generating field for OOUI.
911 * @stable to override
912 * @return string 'left', 'right', 'top' or 'inline'
913 */
914 protected function getLabelAlignOOUI() {
915 return 'top';
916 }
917
918 /**
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
923 */
924 protected function getFieldLayoutOOUI( $inputField, $config ) {
925 return new HTMLFormFieldLayout( $inputField, $config );
926 }
927
928 /**
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
933 *
934 * @return bool
935 */
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();
939 }
940
941 /**
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
945 *
946 * @return string[]
947 */
948 protected function getOOUIModules() {
949 return [];
950 }
951
952 /**
953 * Get the complete raw fields for the input, including help text,
954 * labels, and whatever.
955 * @stable to override
956 * @since 1.20
957 *
958 * @param string $value The value to set the input to.
959 *
960 * @return string Complete HTML table row.
961 */
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() );
968 }
969
970 /**
971 * Get the complete field for the input, including help text,
972 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
973 *
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.
978 */
979 public function getVForm( $value ) {
980 // Ewwww
981 $this->mVFormClass = ' mw-ui-vform-field';
982 return $this->getDiv( $value );
983 }
984
985 /**
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
991 */
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() );
999 }
1000
1001 /**
1002 * Generate help text HTML in table format
1003 * @since 1.20
1004 *
1005 * @param string|null $helptext
1006 * @return string
1007 */
1008 public function getHelpTextHtmlTable( $helptext ) {
1009 if ( $helptext === null ) {
1010 return '';
1011 }
1012
1013 $rowAttributes = [];
1014 if ( $this->mCondState ) {
1015 $rowAttributes['data-cond-state'] = FormatJson::encode( $this->parseCondStateForClient() );
1016 $rowAttributes['class'] = $this->mCondStateClass;
1017 }
1018
1019 $tdClasses = [ 'htmlform-tip' ];
1020 if ( $this->mHelpClass !== false ) {
1021 $tdClasses[] = $this->mHelpClass;
1022 }
1023 return Html::rawElement( 'tr', $rowAttributes,
1024 Html::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext )
1025 );
1026 }
1027
1028 /**
1029 * Generate help text HTML in div format
1030 * @since 1.20
1031 *
1032 * @param string|null $helptext
1033 * @param string[] $cssClasses
1034 *
1035 * @return string
1036 */
1037 public function getHelpTextHtmlDiv( $helptext, $cssClasses = [] ) {
1038 if ( $helptext === null ) {
1039 return '';
1040 }
1041
1042 $wrapperAttributes = [
1043 'class' => array_merge( $cssClasses, [ 'htmlform-tip' ] ),
1044 ];
1045 if ( $this->mHelpClass !== false ) {
1046 $wrapperAttributes['class'][] = $this->mHelpClass;
1047 }
1048 if ( $this->mCondState ) {
1049 $wrapperAttributes['data-cond-state'] = FormatJson::encode( $this->parseCondStateForClient() );
1050 $wrapperAttributes['class'] = array_merge( $wrapperAttributes['class'], $this->mCondStateClass );
1051 }
1052 return Html::rawElement( 'div', $wrapperAttributes, $helptext );
1053 }
1054
1055 /**
1056 * Generate help text HTML formatted for raw output
1057 * @since 1.20
1058 *
1059 * @param string|null $helptext
1060 * @return string
1061 */
1062 public function getHelpTextHtmlRaw( $helptext ) {
1063 return $this->getHelpTextHtmlDiv( $helptext );
1064 }
1065
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'] ) ];
1076 }
1077
1078 return [];
1079 }
1080
1081 /**
1082 * Determine the help text to display
1083 * @stable to override
1084 * @since 1.20
1085 * @return string|null HTML
1086 */
1087 public function getHelpText() {
1088 $html = [];
1089
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();
1097 }
1098 }
1099 }
1100
1101 return $html ? implode( $this->msg( 'word-separator' )->escaped(), $html ) : null;
1102 }
1103
1104 /**
1105 * Determine if the help text should be displayed inline.
1106 *
1107 * Only applies to OOUI forms.
1108 *
1109 * @since 1.31
1110 * @return bool
1111 */
1112 public function isHelpInline() {
1113 return $this->mParams['help-inline'] ?? true;
1114 }
1115
1116 /**
1117 * Determine form errors to display and their classes
1118 * @since 1.20
1119 *
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.
1123 *
1124 * @param string $value The value of the input
1125 * @return array [ $errors, $errorClass ]
1126 * @return-taint none
1127 */
1128 public function getErrorsAndErrorClass( $value ) {
1129 $errors = $this->validate( $value, $this->mParent->mFieldData );
1130
1131 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
1132 return [ '', '' ];
1133 }
1134
1135 return [ self::formatErrors( $errors ), 'mw-htmlform-invalid-input' ];
1136 }
1137
1138 /**
1139 * Determine form errors to display, returning them in an array.
1140 *
1141 * @since 1.26
1142 * @param string $value The value of the input
1143 * @return string[] Array of error HTML strings
1144 */
1145 public function getErrorsRaw( $value ) {
1146 $errors = $this->validate( $value, $this->mParent->mFieldData );
1147
1148 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
1149 return [];
1150 }
1151
1152 if ( !is_array( $errors ) ) {
1153 $errors = [ $errors ];
1154 }
1155 foreach ( $errors as &$error ) {
1156 if ( $error instanceof Message ) {
1157 $error = $error->parse();
1158 }
1159 }
1160
1161 return $errors;
1162 }
1163
1164 /**
1165 * @stable to override
1166 * @return string HTML
1167 */
1168 public function getLabel() {
1169 return $this->mLabel ?? '';
1170 }
1171
1172 /**
1173 * @stable to override
1174 * @param array $cellAttributes
1175 *
1176 * @return string
1177 */
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 ] : [];
1182
1183 $labelValue = trim( $this->getLabel() );
1184 $hasLabel = $labelValue !== '' && $labelValue !== "\u{00A0}" && $labelValue !== '&#160;';
1185
1186 $displayFormat = $this->mParent->getDisplayFormat();
1187 $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
1188
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 );
1200 }
1201 }
1202
1203 return '';
1204 }
1205
1206 /**
1207 * @stable to override
1208 * @return mixed
1209 */
1210 public function getDefault() {
1211 return $this->mDefault ?? null;
1212 }
1213
1214 /**
1215 * Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
1216 *
1217 * @return array Attributes
1218 */
1219 public function getTooltipAndAccessKey() {
1220 if ( empty( $this->mParams['tooltip'] ) ) {
1221 return [];
1222 }
1223
1224 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1225 }
1226
1227 /**
1228 * Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
1229 *
1230 * @return array Attributes
1231 */
1232 public function getTooltipAndAccessKeyOOUI() {
1233 if ( empty( $this->mParams['tooltip'] ) ) {
1234 return [];
1235 }
1236
1237 return [
1238 'title' => Linker::titleAttrib( $this->mParams['tooltip'] ),
1239 'accessKey' => Linker::accesskey( $this->mParams['tooltip'] ),
1240 ];
1241 }
1242
1243 /**
1244 * Returns the given attributes from the parameters
1245 * @stable to override
1246 *
1247 * @param array $list List of attributes to get
1248 * @return array Attributes
1249 */
1250 public function getAttributes( array $list ) {
1251 static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1252
1253 $ret = [];
1254 foreach ( $list as $key ) {
1255 if ( in_array( $key, $boolAttribs ) ) {
1256 if ( !empty( $this->mParams[$key] ) ) {
1257 $ret[$key] = '';
1258 }
1259 } elseif ( isset( $this->mParams[$key] ) ) {
1260 $ret[$key] = $this->mParams[$key];
1261 }
1262 }
1263
1264 return $ret;
1265 }
1266
1267 /**
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.
1270 *
1271 * @param array $options
1272 * @param bool $needsParse
1273 * @return array
1274 * @return-taint tainted
1275 */
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.',
1285 [
1286 'msg_key_one' => $key,
1287 'lang' => $this->mParent ?
1288 $this->mParent->getLanguageCode()->toBcp47Code() :
1289 RequestContext::getMain()->getLanguageCode()->toBcp47Code(),
1290 ]
1291 );
1292 continue;
1293 }
1294 $ret[$msgAsText] = is_array( $value )
1295 ? $this->lookupOptionsKeys( $value, $needsParse )
1296 : strval( $value );
1297 }
1298 return $ret;
1299 }
1300
1301 /**
1302 * Recursively forces values in an array to strings, because issues arise
1303 * with integer 0 as a value.
1304 *
1305 * @param array|string $array
1306 * @return array|string
1307 */
1308 public static function forceToStringRecursive( $array ) {
1309 if ( is_array( $array ) ) {
1310 return array_map( [ __CLASS__, 'forceToStringRecursive' ], $array );
1311 } else {
1312 return strval( $array );
1313 }
1314 }
1315
1316 /**
1317 * Fetch the array of options from the field's parameters. In order, this
1318 * checks 'options-messages', 'options', then 'options-message'.
1319 *
1320 * @return array|null
1321 */
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;
1328 }
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;
1338 }
1339 }
1340
1341 return $this->mOptions;
1342 }
1343
1344 /**
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.
1348 */
1349 public function getOptionsOOUI() {
1350 $oldoptions = $this->getOptions();
1351
1352 if ( $oldoptions === null ) {
1353 return null;
1354 }
1355
1356 return Html::listDropdownOptionsOoui( $oldoptions );
1357 }
1358
1359 /**
1360 * flatten an array of options to a single array, for instance,
1361 * a set of "<options>" inside "<optgroups>".
1362 *
1363 * @param array $options Associative Array with values either Strings or Arrays
1364 * @return array Flattened input
1365 */
1366 public static function flattenOptions( $options ) {
1367 $flatOpts = [];
1368
1369 foreach ( $options as $value ) {
1370 if ( is_array( $value ) ) {
1371 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1372 } else {
1373 $flatOpts[] = $value;
1374 }
1375 }
1376
1377 return $flatOpts;
1378 }
1379
1380 /**
1381 * Formats one or more errors as accepted by field validation-callback.
1382 *
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
1392 */
1393 protected static function formatErrors( $errors ) {
1394 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1395 $errors = array_shift( $errors );
1396 }
1397
1398 if ( is_array( $errors ) ) {
1399 foreach ( $errors as &$error ) {
1400 $error = Html::rawElement( 'li', [],
1401 $error instanceof Message ? $error->parse() : $error
1402 );
1403 }
1404 $errors = Html::rawElement( 'ul', [], implode( "\n", $errors ) );
1405 } elseif ( $errors instanceof Message ) {
1406 $errors = $errors->parse();
1407 }
1408
1409 return Html::errorBox( $errors );
1410 }
1411
1412 /**
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
1417 */
1418 protected function getMessage( $value ) {
1419 $message = Message::newFromSpecifier( $value );
1420
1421 if ( $this->mParent ) {
1422 $message->setContext( $this->mParent );
1423 }
1424
1425 return $message;
1426 }
1427
1428 /**
1429 * Skip this field when collecting data.
1430 * @stable to override
1431 * @param WebRequest $request
1432 * @return bool
1433 * @since 1.27
1434 */
1435 public function skipLoadData( $request ) {
1436 return !empty( $this->mParams['nodata'] );
1437 }
1438
1439 /**
1440 * Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5
1441 * form validation to work correctly.
1442 *
1443 * @return bool
1444 * @since 1.29
1445 */
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;
1449 }
1450 }
1451
1452 /** @deprecated class alias since 1.42 */
1453 class_alias( HTMLFormField::class, 'HTMLFormField' );