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