cd4d4b749f879be635e304b6ba28bf2fe1d713a2
[lhc/web/wiklou.git] / includes / htmlform / HTMLFormField.php
1 <?php
2
3 /**
4 * The parent class to generate form fields. Any field type should
5 * be a subclass of this.
6 */
7 abstract class HTMLFormField {
8 public $mParams;
9
10 protected $mValidationCallback;
11 protected $mFilterCallback;
12 protected $mName;
13 protected $mDir;
14 protected $mLabel; # String label, as HTML. Set on construction.
15 protected $mID;
16 protected $mClass = '';
17 protected $mVFormClass = '';
18 protected $mHelpClass = false;
19 protected $mDefault;
20 /**
21 * @var array|bool|null
22 */
23 protected $mOptions = false;
24 protected $mOptionsLabelsNotFromMessage = false;
25 protected $mHideIf = null;
26
27 /**
28 * @var bool If true will generate an empty div element with no label
29 * @since 1.22
30 */
31 protected $mShowEmptyLabels = true;
32
33 /**
34 * @var HTMLForm|null
35 */
36 public $mParent;
37
38 /**
39 * This function must be implemented to return the HTML to generate
40 * the input object itself. It should not implement the surrounding
41 * table cells/rows, or labels/help messages.
42 *
43 * @param string $value The value to set the input to; eg a default
44 * text for a text input.
45 *
46 * @return string Valid HTML.
47 */
48 abstract public function getInputHTML( $value );
49
50 /**
51 * Same as getInputHTML, but returns an OOUI object.
52 * Defaults to false, which getOOUI will interpret as "use the HTML version"
53 *
54 * @param string $value
55 * @return OOUI\Widget|false
56 */
57 public function getInputOOUI( $value ) {
58 return false;
59 }
60
61 /**
62 * True if this field type is able to display errors; false if validation errors need to be
63 * displayed in the main HTMLForm error area.
64 * @return bool
65 */
66 public function canDisplayErrors() {
67 return $this->hasVisibleOutput();
68 }
69
70 /**
71 * Get a translated interface message
72 *
73 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
74 * and wfMessage() otherwise.
75 *
76 * Parameters are the same as wfMessage().
77 *
78 * @return Message
79 */
80 public function msg() {
81 $args = func_get_args();
82
83 if ( $this->mParent ) {
84 $callback = [ $this->mParent, 'msg' ];
85 } else {
86 $callback = 'wfMessage';
87 }
88
89 return call_user_func_array( $callback, $args );
90 }
91
92 /**
93 * If this field has a user-visible output or not. If not,
94 * it will not be rendered
95 *
96 * @return bool
97 */
98 public function hasVisibleOutput() {
99 return true;
100 }
101
102 /**
103 * Fetch a field value from $alldata for the closest field matching a given
104 * name.
105 *
106 * This is complex because it needs to handle array fields like the user
107 * would expect. The general algorithm is to look for $name as a sibling
108 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
109 * that $name itself might be referencing an array.
110 *
111 * @param array $alldata
112 * @param string $name
113 * @return string
114 */
115 protected function getNearestFieldByName( $alldata, $name ) {
116 $tmp = $this->mName;
117 $thisKeys = [];
118 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
119 array_unshift( $thisKeys, $m[2] );
120 $tmp = $m[1];
121 }
122 if ( substr( $tmp, 0, 2 ) == 'wp' &&
123 !array_key_exists( $tmp, $alldata ) &&
124 array_key_exists( substr( $tmp, 2 ), $alldata )
125 ) {
126 // Adjust for name mangling.
127 $tmp = substr( $tmp, 2 );
128 }
129 array_unshift( $thisKeys, $tmp );
130
131 $tmp = $name;
132 $nameKeys = [];
133 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
134 array_unshift( $nameKeys, $m[2] );
135 $tmp = $m[1];
136 }
137 array_unshift( $nameKeys, $tmp );
138
139 $testValue = '';
140 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
141 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
142 $data = $alldata;
143 while ( $keys ) {
144 $key = array_shift( $keys );
145 if ( !is_array( $data ) || !array_key_exists( $key, $data ) ) {
146 continue 2;
147 }
148 $data = $data[$key];
149 }
150 $testValue = (string)$data;
151 break;
152 }
153
154 return $testValue;
155 }
156
157 /**
158 * Helper function for isHidden to handle recursive data structures.
159 *
160 * @param array $alldata
161 * @param array $params
162 * @return bool
163 * @throws MWException
164 */
165 protected function isHiddenRecurse( array $alldata, array $params ) {
166 $origParams = $params;
167 $op = array_shift( $params );
168
169 try {
170 switch ( $op ) {
171 case 'AND':
172 foreach ( $params as $i => $p ) {
173 if ( !is_array( $p ) ) {
174 throw new MWException(
175 "Expected array, found " . gettype( $p ) . " at index $i"
176 );
177 }
178 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
179 return false;
180 }
181 }
182 return true;
183
184 case 'OR':
185 foreach ( $params as $i => $p ) {
186 if ( !is_array( $p ) ) {
187 throw new MWException(
188 "Expected array, found " . gettype( $p ) . " at index $i"
189 );
190 }
191 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
192 return true;
193 }
194 }
195 return false;
196
197 case 'NAND':
198 foreach ( $params as $i => $p ) {
199 if ( !is_array( $p ) ) {
200 throw new MWException(
201 "Expected array, found " . gettype( $p ) . " at index $i"
202 );
203 }
204 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
205 return true;
206 }
207 }
208 return false;
209
210 case 'NOR':
211 foreach ( $params as $i => $p ) {
212 if ( !is_array( $p ) ) {
213 throw new MWException(
214 "Expected array, found " . gettype( $p ) . " at index $i"
215 );
216 }
217 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
218 return false;
219 }
220 }
221 return true;
222
223 case 'NOT':
224 if ( count( $params ) !== 1 ) {
225 throw new MWException( "NOT takes exactly one parameter" );
226 }
227 $p = $params[0];
228 if ( !is_array( $p ) ) {
229 throw new MWException(
230 "Expected array, found " . gettype( $p ) . " at index 0"
231 );
232 }
233 return !$this->isHiddenRecurse( $alldata, $p );
234
235 case '===':
236 case '!==':
237 if ( count( $params ) !== 2 ) {
238 throw new MWException( "$op takes exactly two parameters" );
239 }
240 list( $field, $value ) = $params;
241 if ( !is_string( $field ) || !is_string( $value ) ) {
242 throw new MWException( "Parameters for $op must be strings" );
243 }
244 $testValue = $this->getNearestFieldByName( $alldata, $field );
245 switch ( $op ) {
246 case '===':
247 return ( $value === $testValue );
248 case '!==':
249 return ( $value !== $testValue );
250 }
251
252 default:
253 throw new MWException( "Unknown operation" );
254 }
255 } catch ( Exception $ex ) {
256 throw new MWException(
257 "Invalid hide-if specification for $this->mName: " .
258 $ex->getMessage() . " in " . var_export( $origParams, true ),
259 0, $ex
260 );
261 }
262 }
263
264 /**
265 * Test whether this field is supposed to be hidden, based on the values of
266 * the other form fields.
267 *
268 * @since 1.23
269 * @param array $alldata The data collected from the form
270 * @return bool
271 */
272 public function isHidden( $alldata ) {
273 if ( !$this->mHideIf ) {
274 return false;
275 }
276
277 return $this->isHiddenRecurse( $alldata, $this->mHideIf );
278 }
279
280 /**
281 * Override this function if the control can somehow trigger a form
282 * submission that shouldn't actually submit the HTMLForm.
283 *
284 * @since 1.23
285 * @param string|array $value The value the field was submitted with
286 * @param array $alldata The data collected from the form
287 *
288 * @return bool True to cancel the submission
289 */
290 public function cancelSubmit( $value, $alldata ) {
291 return false;
292 }
293
294 /**
295 * Override this function to add specific validation checks on the
296 * field input. Don't forget to call parent::validate() to ensure
297 * that the user-defined callback mValidationCallback is still run
298 *
299 * @param string|array $value The value the field was submitted with
300 * @param array $alldata The data collected from the form
301 *
302 * @return bool|string|Message True on success, or String/Message error to display, or
303 * false to fail validation without displaying an error.
304 */
305 public function validate( $value, $alldata ) {
306 if ( $this->isHidden( $alldata ) ) {
307 return true;
308 }
309
310 if ( isset( $this->mParams['required'] )
311 && $this->mParams['required'] !== false
312 && $value === ''
313 ) {
314 return $this->msg( 'htmlform-required' );
315 }
316
317 if ( isset( $this->mValidationCallback ) ) {
318 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
319 }
320
321 return true;
322 }
323
324 public function filter( $value, $alldata ) {
325 if ( isset( $this->mFilterCallback ) ) {
326 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
327 }
328
329 return $value;
330 }
331
332 /**
333 * Should this field have a label, or is there no input element with the
334 * appropriate id for the label to point to?
335 *
336 * @return bool True to output a label, false to suppress
337 */
338 protected function needsLabel() {
339 return true;
340 }
341
342 /**
343 * Tell the field whether to generate a separate label element if its label
344 * is blank.
345 *
346 * @since 1.22
347 *
348 * @param bool $show Set to false to not generate a label.
349 * @return void
350 */
351 public function setShowEmptyLabel( $show ) {
352 $this->mShowEmptyLabels = $show;
353 }
354
355 /**
356 * Can we assume that the request is an attempt to submit a HTMLForm, as opposed to an attempt to
357 * just view it? This can't normally be distinguished for e.g. checkboxes.
358 *
359 * Returns true if the request has a field for a CSRF token (wpEditToken) or a form identifier
360 * (wpFormIdentifier).
361 *
362 * @param WebRequest $request
363 * @return bool
364 */
365 protected function isSubmitAttempt( WebRequest $request ) {
366 return $request->getCheck( 'wpEditToken' ) || $request->getCheck( 'wpFormIdentifier' );
367 }
368
369 /**
370 * Get the value that this input has been set to from a posted form,
371 * or the input's default value if it has not been set.
372 *
373 * @param WebRequest $request
374 * @return string The value
375 */
376 public function loadDataFromRequest( $request ) {
377 if ( $request->getCheck( $this->mName ) ) {
378 return $request->getText( $this->mName );
379 } else {
380 return $this->getDefault();
381 }
382 }
383
384 /**
385 * Initialise the object
386 *
387 * @param array $params Associative Array. See HTMLForm doc for syntax.
388 *
389 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
390 * @throws MWException
391 */
392 public function __construct( $params ) {
393 $this->mParams = $params;
394
395 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm ) {
396 $this->mParent = $params['parent'];
397 }
398
399 # Generate the label from a message, if possible
400 if ( isset( $params['label-message'] ) ) {
401 $this->mLabel = $this->getMessage( $params['label-message'] )->parse();
402 } elseif ( isset( $params['label'] ) ) {
403 if ( $params['label'] === '&#160;' ) {
404 // Apparently some things set &nbsp directly and in an odd format
405 $this->mLabel = '&#160;';
406 } else {
407 $this->mLabel = htmlspecialchars( $params['label'] );
408 }
409 } elseif ( isset( $params['label-raw'] ) ) {
410 $this->mLabel = $params['label-raw'];
411 }
412
413 $this->mName = "wp{$params['fieldname']}";
414 if ( isset( $params['name'] ) ) {
415 $this->mName = $params['name'];
416 }
417
418 if ( isset( $params['dir'] ) ) {
419 $this->mDir = $params['dir'];
420 }
421
422 $validName = urlencode( $this->mName );
423 $validName = str_replace( [ '%5B', '%5D' ], [ '[', ']' ], $validName );
424 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
425 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
426 }
427
428 $this->mID = "mw-input-{$this->mName}";
429
430 if ( isset( $params['default'] ) ) {
431 $this->mDefault = $params['default'];
432 }
433
434 if ( isset( $params['id'] ) ) {
435 $id = $params['id'];
436 $validId = urlencode( $id );
437
438 if ( $id != $validId ) {
439 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
440 }
441
442 $this->mID = $id;
443 }
444
445 if ( isset( $params['cssclass'] ) ) {
446 $this->mClass = $params['cssclass'];
447 }
448
449 if ( isset( $params['csshelpclass'] ) ) {
450 $this->mHelpClass = $params['csshelpclass'];
451 }
452
453 if ( isset( $params['validation-callback'] ) ) {
454 $this->mValidationCallback = $params['validation-callback'];
455 }
456
457 if ( isset( $params['filter-callback'] ) ) {
458 $this->mFilterCallback = $params['filter-callback'];
459 }
460
461 if ( isset( $params['hidelabel'] ) ) {
462 $this->mShowEmptyLabels = false;
463 }
464
465 if ( isset( $params['hide-if'] ) ) {
466 $this->mHideIf = $params['hide-if'];
467 }
468 }
469
470 /**
471 * Get the complete table row for the input, including help text,
472 * labels, and whatever.
473 *
474 * @param string $value The value to set the input to.
475 *
476 * @return string Complete HTML table row.
477 */
478 public function getTableRow( $value ) {
479 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
480 $inputHtml = $this->getInputHTML( $value );
481 $fieldType = static::class;
482 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
483 $cellAttributes = [];
484 $rowAttributes = [];
485 $rowClasses = '';
486
487 if ( !empty( $this->mParams['vertical-label'] ) ) {
488 $cellAttributes['colspan'] = 2;
489 $verticalLabel = true;
490 } else {
491 $verticalLabel = false;
492 }
493
494 $label = $this->getLabelHtml( $cellAttributes );
495
496 $field = Html::rawElement(
497 'td',
498 [ 'class' => 'mw-input' ] + $cellAttributes,
499 $inputHtml . "\n$errors"
500 );
501
502 if ( $this->mHideIf ) {
503 $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
504 $rowClasses .= ' mw-htmlform-hide-if';
505 }
506
507 if ( $verticalLabel ) {
508 $html = Html::rawElement( 'tr',
509 $rowAttributes + [ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
510 $html .= Html::rawElement( 'tr',
511 $rowAttributes + [
512 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
513 ],
514 $field );
515 } else {
516 $html =
517 Html::rawElement( 'tr',
518 $rowAttributes + [
519 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
520 ],
521 $label . $field );
522 }
523
524 return $html . $helptext;
525 }
526
527 /**
528 * Get the complete div for the input, including help text,
529 * labels, and whatever.
530 * @since 1.20
531 *
532 * @param string $value The value to set the input to.
533 *
534 * @return string Complete HTML table row.
535 */
536 public function getDiv( $value ) {
537 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
538 $inputHtml = $this->getInputHTML( $value );
539 $fieldType = static::class;
540 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
541 $cellAttributes = [];
542 $label = $this->getLabelHtml( $cellAttributes );
543
544 $outerDivClass = [
545 'mw-input',
546 'mw-htmlform-nolabel' => ( $label === '' )
547 ];
548
549 $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
550
551 if ( $horizontalLabel ) {
552 $field = '&#160;' . $inputHtml . "\n$errors";
553 } else {
554 $field = Html::rawElement(
555 'div',
556 [ 'class' => $outerDivClass ] + $cellAttributes,
557 $inputHtml . "\n$errors"
558 );
559 }
560 $divCssClasses = [ "mw-htmlform-field-$fieldType",
561 $this->mClass, $this->mVFormClass, $errorClass ];
562
563 $wrapperAttributes = [
564 'class' => $divCssClasses,
565 ];
566 if ( $this->mHideIf ) {
567 $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
568 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
569 }
570 $html = Html::rawElement( 'div', $wrapperAttributes, $label . $field );
571 $html .= $helptext;
572
573 return $html;
574 }
575
576 /**
577 * Get the OOUI version of the div. Falls back to getDiv by default.
578 * @since 1.26
579 *
580 * @param string $value The value to set the input to.
581 *
582 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
583 */
584 public function getOOUI( $value ) {
585 $inputField = $this->getInputOOUI( $value );
586
587 if ( !$inputField ) {
588 // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
589 // generate the whole field, label and errors and all, then wrap it in a Widget.
590 // It might look weird, but it'll work OK.
591 return $this->getFieldLayoutOOUI(
592 new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $this->getDiv( $value ) ) ] ),
593 [ 'infusable' => false, 'align' => 'top' ]
594 );
595 }
596
597 $infusable = true;
598 if ( is_string( $inputField ) ) {
599 // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
600 // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
601 // JavaScript doesn't know how to rebuilt the contents.
602 $inputField = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $inputField ) ] );
603 $infusable = false;
604 }
605
606 $fieldType = static::class;
607 $help = $this->getHelpText();
608 $errors = $this->getErrorsRaw( $value );
609 foreach ( $errors as &$error ) {
610 $error = new OOUI\HtmlSnippet( $error );
611 }
612
613 $notices = $this->getNotices();
614 foreach ( $notices as &$notice ) {
615 $notice = new OOUI\HtmlSnippet( $notice );
616 }
617
618 $config = [
619 'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass ],
620 'align' => $this->getLabelAlignOOUI(),
621 'help' => ( $help !== null && $help !== '' ) ? new OOUI\HtmlSnippet( $help ) : null,
622 'errors' => $errors,
623 'notices' => $notices,
624 'infusable' => $infusable,
625 ];
626
627 $preloadModules = false;
628
629 if ( $infusable && $this->shouldInfuseOOUI() ) {
630 $preloadModules = true;
631 $config['classes'][] = 'mw-htmlform-field-autoinfuse';
632 }
633
634 // the element could specify, that the label doesn't need to be added
635 $label = $this->getLabel();
636 if ( $label && $label !== '&#160;' ) {
637 $config['label'] = new OOUI\HtmlSnippet( $label );
638 }
639
640 if ( $this->mHideIf ) {
641 $preloadModules = true;
642 $config['hideIf'] = $this->mHideIf;
643 }
644
645 $config['modules'] = $this->getOOUIModules();
646
647 if ( $preloadModules ) {
648 $this->mParent->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
649 $this->mParent->getOutput()->addModules( $this->getOOUIModules() );
650 }
651
652 return $this->getFieldLayoutOOUI( $inputField, $config );
653 }
654
655 /**
656 * Get label alignment when generating field for OOUI.
657 * @return string 'left', 'right', 'top' or 'inline'
658 */
659 protected function getLabelAlignOOUI() {
660 return 'top';
661 }
662
663 /**
664 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
665 * @param string $inputField
666 * @param array $config
667 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
668 */
669 protected function getFieldLayoutOOUI( $inputField, $config ) {
670 if ( isset( $this->mClassWithButton ) ) {
671 $buttonWidget = $this->mClassWithButton->getInputOOUI( '' );
672 return new HTMLFormActionFieldLayout( $inputField, $buttonWidget, $config );
673 }
674 return new HTMLFormFieldLayout( $inputField, $config );
675 }
676
677 /**
678 * Whether the field should be automatically infused. Note that all OOUI HTMLForm fields are
679 * infusable (you can call OO.ui.infuse() on them), but not all are infused by default, since
680 * there is no benefit in doing it e.g. for buttons and it's a small performance hit on page load.
681 *
682 * @return bool
683 */
684 protected function shouldInfuseOOUI() {
685 // Always infuse fields with help text, since the interface for it is nicer with JS
686 return $this->getHelpText() !== null;
687 }
688
689 /**
690 * Get the list of extra ResourceLoader modules which must be loaded client-side before it's
691 * possible to infuse this field's OOUI widget.
692 *
693 * @return string[]
694 */
695 protected function getOOUIModules() {
696 return [];
697 }
698
699 /**
700 * Get the complete raw fields for the input, including help text,
701 * labels, and whatever.
702 * @since 1.20
703 *
704 * @param string $value The value to set the input to.
705 *
706 * @return string Complete HTML table row.
707 */
708 public function getRaw( $value ) {
709 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
710 $inputHtml = $this->getInputHTML( $value );
711 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
712 $cellAttributes = [];
713 $label = $this->getLabelHtml( $cellAttributes );
714
715 $html = "\n$errors";
716 $html .= $label;
717 $html .= $inputHtml;
718 $html .= $helptext;
719
720 return $html;
721 }
722
723 /**
724 * Get the complete field for the input, including help text,
725 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
726 *
727 * @since 1.25
728 * @param string $value The value to set the input to.
729 * @return string Complete HTML field.
730 */
731 public function getVForm( $value ) {
732 // Ewwww
733 $this->mVFormClass = ' mw-ui-vform-field';
734 return $this->getDiv( $value );
735 }
736
737 /**
738 * Get the complete field as an inline element.
739 * @since 1.25
740 * @param string $value The value to set the input to.
741 * @return string Complete HTML inline element
742 */
743 public function getInline( $value ) {
744 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
745 $inputHtml = $this->getInputHTML( $value );
746 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
747 $cellAttributes = [];
748 $label = $this->getLabelHtml( $cellAttributes );
749
750 $html = "\n" . $errors .
751 $label . '&#160;' .
752 $inputHtml .
753 $helptext;
754
755 return $html;
756 }
757
758 /**
759 * Generate help text HTML in table format
760 * @since 1.20
761 *
762 * @param string|null $helptext
763 * @return string
764 */
765 public function getHelpTextHtmlTable( $helptext ) {
766 if ( is_null( $helptext ) ) {
767 return '';
768 }
769
770 $rowAttributes = [];
771 if ( $this->mHideIf ) {
772 $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
773 $rowAttributes['class'] = 'mw-htmlform-hide-if';
774 }
775
776 $tdClasses = [ 'htmlform-tip' ];
777 if ( $this->mHelpClass !== false ) {
778 $tdClasses[] = $this->mHelpClass;
779 }
780 $row = Html::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
781 $row = Html::rawElement( 'tr', $rowAttributes, $row );
782
783 return $row;
784 }
785
786 /**
787 * Generate help text HTML in div format
788 * @since 1.20
789 *
790 * @param string|null $helptext
791 *
792 * @return string
793 */
794 public function getHelpTextHtmlDiv( $helptext ) {
795 if ( is_null( $helptext ) ) {
796 return '';
797 }
798
799 $wrapperAttributes = [
800 'class' => 'htmlform-tip',
801 ];
802 if ( $this->mHelpClass !== false ) {
803 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
804 }
805 if ( $this->mHideIf ) {
806 $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
807 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
808 }
809 $div = Html::rawElement( 'div', $wrapperAttributes, $helptext );
810
811 return $div;
812 }
813
814 /**
815 * Generate help text HTML formatted for raw output
816 * @since 1.20
817 *
818 * @param string|null $helptext
819 * @return string
820 */
821 public function getHelpTextHtmlRaw( $helptext ) {
822 return $this->getHelpTextHtmlDiv( $helptext );
823 }
824
825 /**
826 * Determine the help text to display
827 * @since 1.20
828 * @return string|null HTML
829 */
830 public function getHelpText() {
831 $helptext = null;
832
833 if ( isset( $this->mParams['help-message'] ) ) {
834 $this->mParams['help-messages'] = [ $this->mParams['help-message'] ];
835 }
836
837 if ( isset( $this->mParams['help-messages'] ) ) {
838 foreach ( $this->mParams['help-messages'] as $msg ) {
839 $msg = $this->getMessage( $msg );
840
841 if ( $msg->exists() ) {
842 if ( is_null( $helptext ) ) {
843 $helptext = '';
844 } else {
845 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
846 }
847 $helptext .= $msg->parse(); // Append message
848 }
849 }
850 } elseif ( isset( $this->mParams['help'] ) ) {
851 $helptext = $this->mParams['help'];
852 }
853
854 return $helptext;
855 }
856
857 /**
858 * Determine form errors to display and their classes
859 * @since 1.20
860 *
861 * @param string $value The value of the input
862 * @return array array( $errors, $errorClass )
863 */
864 public function getErrorsAndErrorClass( $value ) {
865 $errors = $this->validate( $value, $this->mParent->mFieldData );
866
867 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
868 $errors = '';
869 $errorClass = '';
870 } else {
871 $errors = self::formatErrors( $errors );
872 $errorClass = 'mw-htmlform-invalid-input';
873 }
874
875 return [ $errors, $errorClass ];
876 }
877
878 /**
879 * Determine form errors to display, returning them in an array.
880 *
881 * @since 1.26
882 * @param string $value The value of the input
883 * @return string[] Array of error HTML strings
884 */
885 public function getErrorsRaw( $value ) {
886 $errors = $this->validate( $value, $this->mParent->mFieldData );
887
888 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
889 $errors = [];
890 }
891
892 if ( !is_array( $errors ) ) {
893 $errors = [ $errors ];
894 }
895 foreach ( $errors as &$error ) {
896 if ( $error instanceof Message ) {
897 $error = $error->parse();
898 }
899 }
900
901 return $errors;
902 }
903
904 /**
905 * Determine notices to display for the field.
906 *
907 * @since 1.28
908 * @return string[]
909 */
910 public function getNotices() {
911 $notices = [];
912
913 if ( isset( $this->mParams['notice-message'] ) ) {
914 $notices[] = $this->getMessage( $this->mParams['notice-message'] )->parse();
915 }
916
917 if ( isset( $this->mParams['notice-messages'] ) ) {
918 foreach ( $this->mParams['notice-messages'] as $msg ) {
919 $notices[] = $this->getMessage( $msg )->parse();
920 }
921 } elseif ( isset( $this->mParams['notice'] ) ) {
922 $notices[] = $this->mParams['notice'];
923 }
924
925 return $notices;
926 }
927
928 /**
929 * @return string HTML
930 */
931 public function getLabel() {
932 return is_null( $this->mLabel ) ? '' : $this->mLabel;
933 }
934
935 public function getLabelHtml( $cellAttributes = [] ) {
936 # Don't output a for= attribute for labels with no associated input.
937 # Kind of hacky here, possibly we don't want these to be <label>s at all.
938 $for = [];
939
940 if ( $this->needsLabel() ) {
941 $for['for'] = $this->mID;
942 }
943
944 $labelValue = trim( $this->getLabel() );
945 $hasLabel = false;
946 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
947 $hasLabel = true;
948 }
949
950 $displayFormat = $this->mParent->getDisplayFormat();
951 $html = '';
952 $horizontalLabel = $this->mParams['horizontal-label'] ?? false;
953
954 if ( $displayFormat === 'table' ) {
955 $html =
956 Html::rawElement( 'td',
957 [ 'class' => 'mw-label' ] + $cellAttributes,
958 Html::rawElement( 'label', $for, $labelValue ) );
959 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
960 if ( $displayFormat === 'div' && !$horizontalLabel ) {
961 $html =
962 Html::rawElement( 'div',
963 [ 'class' => 'mw-label' ] + $cellAttributes,
964 Html::rawElement( 'label', $for, $labelValue ) );
965 } else {
966 $html = Html::rawElement( 'label', $for, $labelValue );
967 }
968 }
969
970 return $html;
971 }
972
973 public function getDefault() {
974 if ( isset( $this->mDefault ) ) {
975 return $this->mDefault;
976 } else {
977 return null;
978 }
979 }
980
981 /**
982 * Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
983 *
984 * @return array Attributes
985 */
986 public function getTooltipAndAccessKey() {
987 if ( empty( $this->mParams['tooltip'] ) ) {
988 return [];
989 }
990
991 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
992 }
993
994 /**
995 * Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
996 *
997 * @return array Attributes
998 */
999 public function getTooltipAndAccessKeyOOUI() {
1000 if ( empty( $this->mParams['tooltip'] ) ) {
1001 return [];
1002 }
1003
1004 return [
1005 'title' => Linker::titleAttrib( $this->mParams['tooltip'] ),
1006 'accessKey' => Linker::accesskey( $this->mParams['tooltip'] ),
1007 ];
1008 }
1009
1010 /**
1011 * Returns the given attributes from the parameters
1012 *
1013 * @param array $list List of attributes to get
1014 * @return array Attributes
1015 */
1016 public function getAttributes( array $list ) {
1017 static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1018
1019 $ret = [];
1020 foreach ( $list as $key ) {
1021 if ( in_array( $key, $boolAttribs ) ) {
1022 if ( !empty( $this->mParams[$key] ) ) {
1023 $ret[$key] = '';
1024 }
1025 } elseif ( isset( $this->mParams[$key] ) ) {
1026 $ret[$key] = $this->mParams[$key];
1027 }
1028 }
1029
1030 return $ret;
1031 }
1032
1033 /**
1034 * Given an array of msg-key => value mappings, returns an array with keys
1035 * being the message texts. It also forces values to strings.
1036 *
1037 * @param array $options
1038 * @return array
1039 */
1040 private function lookupOptionsKeys( $options ) {
1041 $ret = [];
1042 foreach ( $options as $key => $value ) {
1043 $key = $this->msg( $key )->plain();
1044 $ret[$key] = is_array( $value )
1045 ? $this->lookupOptionsKeys( $value )
1046 : strval( $value );
1047 }
1048 return $ret;
1049 }
1050
1051 /**
1052 * Recursively forces values in an array to strings, because issues arise
1053 * with integer 0 as a value.
1054 *
1055 * @param array $array
1056 * @return array|string
1057 */
1058 public static function forceToStringRecursive( $array ) {
1059 if ( is_array( $array ) ) {
1060 return array_map( [ __CLASS__, 'forceToStringRecursive' ], $array );
1061 } else {
1062 return strval( $array );
1063 }
1064 }
1065
1066 /**
1067 * Fetch the array of options from the field's parameters. In order, this
1068 * checks 'options-messages', 'options', then 'options-message'.
1069 *
1070 * @return array|null Options array
1071 */
1072 public function getOptions() {
1073 if ( $this->mOptions === false ) {
1074 if ( array_key_exists( 'options-messages', $this->mParams ) ) {
1075 $this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'] );
1076 } elseif ( array_key_exists( 'options', $this->mParams ) ) {
1077 $this->mOptionsLabelsNotFromMessage = true;
1078 $this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
1079 } elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
1080 $message = $this->getMessage( $this->mParams['options-message'] )->inContentLanguage()->plain();
1081 $this->mOptions = Xml::listDropDownOptions( $message );
1082 } else {
1083 $this->mOptions = null;
1084 }
1085 }
1086
1087 return $this->mOptions;
1088 }
1089
1090 /**
1091 * Get options and make them into arrays suitable for OOUI.
1092 * @return array Options for inclusion in a select or whatever.
1093 */
1094 public function getOptionsOOUI() {
1095 $oldoptions = $this->getOptions();
1096
1097 if ( $oldoptions === null ) {
1098 return null;
1099 }
1100
1101 return Xml::listDropDownOptionsOoui( $oldoptions );
1102 }
1103
1104 /**
1105 * flatten an array of options to a single array, for instance,
1106 * a set of "<options>" inside "<optgroups>".
1107 *
1108 * @param array $options Associative Array with values either Strings or Arrays
1109 * @return array Flattened input
1110 */
1111 public static function flattenOptions( $options ) {
1112 $flatOpts = [];
1113
1114 foreach ( $options as $value ) {
1115 if ( is_array( $value ) ) {
1116 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1117 } else {
1118 $flatOpts[] = $value;
1119 }
1120 }
1121
1122 return $flatOpts;
1123 }
1124
1125 /**
1126 * Formats one or more errors as accepted by field validation-callback.
1127 *
1128 * @param string|Message|array $errors Array of strings or Message instances
1129 * @return string HTML
1130 * @since 1.18
1131 */
1132 protected static function formatErrors( $errors ) {
1133 // Note: If you change the logic in this method, change
1134 // htmlform.Checker.js to match.
1135
1136 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1137 $errors = array_shift( $errors );
1138 }
1139
1140 if ( is_array( $errors ) ) {
1141 $lines = [];
1142 foreach ( $errors as $error ) {
1143 if ( $error instanceof Message ) {
1144 $lines[] = Html::rawElement( 'li', [], $error->parse() );
1145 } else {
1146 $lines[] = Html::rawElement( 'li', [], $error );
1147 }
1148 }
1149
1150 return Html::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1151 } else {
1152 if ( $errors instanceof Message ) {
1153 $errors = $errors->parse();
1154 }
1155
1156 return Html::rawElement( 'span', [ 'class' => 'error' ], $errors );
1157 }
1158 }
1159
1160 /**
1161 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1162 * name + parameters array) into a Message.
1163 * @param mixed $value
1164 * @return Message
1165 */
1166 protected function getMessage( $value ) {
1167 $message = Message::newFromSpecifier( $value );
1168
1169 if ( $this->mParent ) {
1170 $message->setContext( $this->mParent );
1171 }
1172
1173 return $message;
1174 }
1175
1176 /**
1177 * Skip this field when collecting data.
1178 * @param WebRequest $request
1179 * @return bool
1180 * @since 1.27
1181 */
1182 public function skipLoadData( $request ) {
1183 return !empty( $this->mParams['nodata'] );
1184 }
1185
1186 /**
1187 * Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5
1188 * form validation to work correctly.
1189 *
1190 * @return bool
1191 * @since 1.29
1192 */
1193 public function needsJSForHtml5FormValidation() {
1194 if ( $this->mHideIf ) {
1195 // This is probably more restrictive than it needs to be, but better safe than sorry
1196 return true;
1197 }
1198 return false;
1199 }
1200 }