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