Merge "Strip soft hyphens (U+00AD) from title"
[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 = isset( $this->mParams['horizontal-label'] )
550 ? $this->mParams['horizontal-label'] : false;
551
552 if ( $horizontalLabel ) {
553 $field = '&#160;' . $inputHtml . "\n$errors";
554 } else {
555 $field = Html::rawElement(
556 'div',
557 [ 'class' => $outerDivClass ] + $cellAttributes,
558 $inputHtml . "\n$errors"
559 );
560 }
561 $divCssClasses = [ "mw-htmlform-field-$fieldType",
562 $this->mClass, $this->mVFormClass, $errorClass ];
563
564 $wrapperAttributes = [
565 'class' => $divCssClasses,
566 ];
567 if ( $this->mHideIf ) {
568 $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
569 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
570 }
571 $html = Html::rawElement( 'div', $wrapperAttributes, $label . $field );
572 $html .= $helptext;
573
574 return $html;
575 }
576
577 /**
578 * Get the OOUI version of the div. Falls back to getDiv by default.
579 * @since 1.26
580 *
581 * @param string $value The value to set the input to.
582 *
583 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
584 */
585 public function getOOUI( $value ) {
586 $inputField = $this->getInputOOUI( $value );
587
588 if ( !$inputField ) {
589 // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
590 // generate the whole field, label and errors and all, then wrap it in a Widget.
591 // It might look weird, but it'll work OK.
592 return $this->getFieldLayoutOOUI(
593 new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $this->getDiv( $value ) ) ] ),
594 [ 'infusable' => false, 'align' => 'top' ]
595 );
596 }
597
598 $infusable = true;
599 if ( is_string( $inputField ) ) {
600 // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
601 // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
602 // JavaScript doesn't know how to rebuilt the contents.
603 $inputField = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $inputField ) ] );
604 $infusable = false;
605 }
606
607 $fieldType = static::class;
608 $help = $this->getHelpText();
609 $errors = $this->getErrorsRaw( $value );
610 foreach ( $errors as &$error ) {
611 $error = new OOUI\HtmlSnippet( $error );
612 }
613
614 $notices = $this->getNotices();
615 foreach ( $notices as &$notice ) {
616 $notice = new OOUI\HtmlSnippet( $notice );
617 }
618
619 $config = [
620 'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass ],
621 'align' => $this->getLabelAlignOOUI(),
622 'help' => ( $help !== null && $help !== '' ) ? new OOUI\HtmlSnippet( $help ) : null,
623 'errors' => $errors,
624 'notices' => $notices,
625 'infusable' => $infusable,
626 ];
627
628 $preloadModules = false;
629
630 if ( $infusable && $this->shouldInfuseOOUI() ) {
631 $preloadModules = true;
632 $config['classes'][] = 'mw-htmlform-field-autoinfuse';
633 }
634
635 // the element could specify, that the label doesn't need to be added
636 $label = $this->getLabel();
637 if ( $label && $label !== '&#160;' ) {
638 $config['label'] = new OOUI\HtmlSnippet( $label );
639 }
640
641 if ( $this->mHideIf ) {
642 $preloadModules = true;
643 $config['hideIf'] = $this->mHideIf;
644 }
645
646 $config['modules'] = $this->getOOUIModules();
647
648 if ( $preloadModules ) {
649 $this->mParent->getOutput()->addModules( 'mediawiki.htmlform.ooui' );
650 $this->mParent->getOutput()->addModules( $this->getOOUIModules() );
651 }
652
653 return $this->getFieldLayoutOOUI( $inputField, $config );
654 }
655
656 /**
657 * Get label alignment when generating field for OOUI.
658 * @return string 'left', 'right', 'top' or 'inline'
659 */
660 protected function getLabelAlignOOUI() {
661 return 'top';
662 }
663
664 /**
665 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
666 * @param string $inputField
667 * @param array $config
668 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
669 */
670 protected function getFieldLayoutOOUI( $inputField, $config ) {
671 if ( isset( $this->mClassWithButton ) ) {
672 $buttonWidget = $this->mClassWithButton->getInputOOUI( '' );
673 return new HTMLFormActionFieldLayout( $inputField, $buttonWidget, $config );
674 }
675 return new HTMLFormFieldLayout( $inputField, $config );
676 }
677
678 /**
679 * Whether the field should be automatically infused. Note that all OOUI HTMLForm fields are
680 * infusable (you can call OO.ui.infuse() on them), but not all are infused by default, since
681 * there is no benefit in doing it e.g. for buttons and it's a small performance hit on page load.
682 *
683 * @return bool
684 */
685 protected function shouldInfuseOOUI() {
686 // Always infuse fields with help text, since the interface for it is nicer with JS
687 return $this->getHelpText() !== null;
688 }
689
690 /**
691 * Get the list of extra ResourceLoader modules which must be loaded client-side before it's
692 * possible to infuse this field's OOUI widget.
693 *
694 * @return string[]
695 */
696 protected function getOOUIModules() {
697 return [];
698 }
699
700 /**
701 * Get the complete raw fields for the input, including help text,
702 * labels, and whatever.
703 * @since 1.20
704 *
705 * @param string $value The value to set the input to.
706 *
707 * @return string Complete HTML table row.
708 */
709 public function getRaw( $value ) {
710 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
711 $inputHtml = $this->getInputHTML( $value );
712 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
713 $cellAttributes = [];
714 $label = $this->getLabelHtml( $cellAttributes );
715
716 $html = "\n$errors";
717 $html .= $label;
718 $html .= $inputHtml;
719 $html .= $helptext;
720
721 return $html;
722 }
723
724 /**
725 * Get the complete field for the input, including help text,
726 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
727 *
728 * @since 1.25
729 * @param string $value The value to set the input to.
730 * @return string Complete HTML field.
731 */
732 public function getVForm( $value ) {
733 // Ewwww
734 $this->mVFormClass = ' mw-ui-vform-field';
735 return $this->getDiv( $value );
736 }
737
738 /**
739 * Get the complete field as an inline element.
740 * @since 1.25
741 * @param string $value The value to set the input to.
742 * @return string Complete HTML inline element
743 */
744 public function getInline( $value ) {
745 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
746 $inputHtml = $this->getInputHTML( $value );
747 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
748 $cellAttributes = [];
749 $label = $this->getLabelHtml( $cellAttributes );
750
751 $html = "\n" . $errors .
752 $label . '&#160;' .
753 $inputHtml .
754 $helptext;
755
756 return $html;
757 }
758
759 /**
760 * Generate help text HTML in table format
761 * @since 1.20
762 *
763 * @param string|null $helptext
764 * @return string
765 */
766 public function getHelpTextHtmlTable( $helptext ) {
767 if ( is_null( $helptext ) ) {
768 return '';
769 }
770
771 $rowAttributes = [];
772 if ( $this->mHideIf ) {
773 $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
774 $rowAttributes['class'] = 'mw-htmlform-hide-if';
775 }
776
777 $tdClasses = [ 'htmlform-tip' ];
778 if ( $this->mHelpClass !== false ) {
779 $tdClasses[] = $this->mHelpClass;
780 }
781 $row = Html::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
782 $row = Html::rawElement( 'tr', $rowAttributes, $row );
783
784 return $row;
785 }
786
787 /**
788 * Generate help text HTML in div format
789 * @since 1.20
790 *
791 * @param string|null $helptext
792 *
793 * @return string
794 */
795 public function getHelpTextHtmlDiv( $helptext ) {
796 if ( is_null( $helptext ) ) {
797 return '';
798 }
799
800 $wrapperAttributes = [
801 'class' => 'htmlform-tip',
802 ];
803 if ( $this->mHelpClass !== false ) {
804 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
805 }
806 if ( $this->mHideIf ) {
807 $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
808 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
809 }
810 $div = Html::rawElement( 'div', $wrapperAttributes, $helptext );
811
812 return $div;
813 }
814
815 /**
816 * Generate help text HTML formatted for raw output
817 * @since 1.20
818 *
819 * @param string|null $helptext
820 * @return string
821 */
822 public function getHelpTextHtmlRaw( $helptext ) {
823 return $this->getHelpTextHtmlDiv( $helptext );
824 }
825
826 /**
827 * Determine the help text to display
828 * @since 1.20
829 * @return string|null HTML
830 */
831 public function getHelpText() {
832 $helptext = null;
833
834 if ( isset( $this->mParams['help-message'] ) ) {
835 $this->mParams['help-messages'] = [ $this->mParams['help-message'] ];
836 }
837
838 if ( isset( $this->mParams['help-messages'] ) ) {
839 foreach ( $this->mParams['help-messages'] as $msg ) {
840 $msg = $this->getMessage( $msg );
841
842 if ( $msg->exists() ) {
843 if ( is_null( $helptext ) ) {
844 $helptext = '';
845 } else {
846 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
847 }
848 $helptext .= $msg->parse(); // Append message
849 }
850 }
851 } elseif ( isset( $this->mParams['help'] ) ) {
852 $helptext = $this->mParams['help'];
853 }
854
855 return $helptext;
856 }
857
858 /**
859 * Determine form errors to display and their classes
860 * @since 1.20
861 *
862 * @param string $value The value of the input
863 * @return array array( $errors, $errorClass )
864 */
865 public function getErrorsAndErrorClass( $value ) {
866 $errors = $this->validate( $value, $this->mParent->mFieldData );
867
868 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
869 $errors = '';
870 $errorClass = '';
871 } else {
872 $errors = self::formatErrors( $errors );
873 $errorClass = 'mw-htmlform-invalid-input';
874 }
875
876 return [ $errors, $errorClass ];
877 }
878
879 /**
880 * Determine form errors to display, returning them in an array.
881 *
882 * @since 1.26
883 * @param string $value The value of the input
884 * @return string[] Array of error HTML strings
885 */
886 public function getErrorsRaw( $value ) {
887 $errors = $this->validate( $value, $this->mParent->mFieldData );
888
889 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
890 $errors = [];
891 }
892
893 if ( !is_array( $errors ) ) {
894 $errors = [ $errors ];
895 }
896 foreach ( $errors as &$error ) {
897 if ( $error instanceof Message ) {
898 $error = $error->parse();
899 }
900 }
901
902 return $errors;
903 }
904
905 /**
906 * Determine notices to display for the field.
907 *
908 * @since 1.28
909 * @return string[]
910 */
911 public function getNotices() {
912 $notices = [];
913
914 if ( isset( $this->mParams['notice-message'] ) ) {
915 $notices[] = $this->getMessage( $this->mParams['notice-message'] )->parse();
916 }
917
918 if ( isset( $this->mParams['notice-messages'] ) ) {
919 foreach ( $this->mParams['notice-messages'] as $msg ) {
920 $notices[] = $this->getMessage( $msg )->parse();
921 }
922 } elseif ( isset( $this->mParams['notice'] ) ) {
923 $notices[] = $this->mParams['notice'];
924 }
925
926 return $notices;
927 }
928
929 /**
930 * @return string HTML
931 */
932 public function getLabel() {
933 return is_null( $this->mLabel ) ? '' : $this->mLabel;
934 }
935
936 public function getLabelHtml( $cellAttributes = [] ) {
937 # Don't output a for= attribute for labels with no associated input.
938 # Kind of hacky here, possibly we don't want these to be <label>s at all.
939 $for = [];
940
941 if ( $this->needsLabel() ) {
942 $for['for'] = $this->mID;
943 }
944
945 $labelValue = trim( $this->getLabel() );
946 $hasLabel = false;
947 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
948 $hasLabel = true;
949 }
950
951 $displayFormat = $this->mParent->getDisplayFormat();
952 $html = '';
953 $horizontalLabel = isset( $this->mParams['horizontal-label'] )
954 ? $this->mParams['horizontal-label'] : false;
955
956 if ( $displayFormat === 'table' ) {
957 $html =
958 Html::rawElement( 'td',
959 [ 'class' => 'mw-label' ] + $cellAttributes,
960 Html::rawElement( 'label', $for, $labelValue ) );
961 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
962 if ( $displayFormat === 'div' && !$horizontalLabel ) {
963 $html =
964 Html::rawElement( 'div',
965 [ 'class' => 'mw-label' ] + $cellAttributes,
966 Html::rawElement( 'label', $for, $labelValue ) );
967 } else {
968 $html = Html::rawElement( 'label', $for, $labelValue );
969 }
970 }
971
972 return $html;
973 }
974
975 public function getDefault() {
976 if ( isset( $this->mDefault ) ) {
977 return $this->mDefault;
978 } else {
979 return null;
980 }
981 }
982
983 /**
984 * Returns the attributes required for the tooltip and accesskey, for Html::element() etc.
985 *
986 * @return array Attributes
987 */
988 public function getTooltipAndAccessKey() {
989 if ( empty( $this->mParams['tooltip'] ) ) {
990 return [];
991 }
992
993 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
994 }
995
996 /**
997 * Returns the attributes required for the tooltip and accesskey, for OOUI widgets' config.
998 *
999 * @return array Attributes
1000 */
1001 public function getTooltipAndAccessKeyOOUI() {
1002 if ( empty( $this->mParams['tooltip'] ) ) {
1003 return [];
1004 }
1005
1006 return [
1007 'title' => Linker::titleAttrib( $this->mParams['tooltip'] ),
1008 'accessKey' => Linker::accesskey( $this->mParams['tooltip'] ),
1009 ];
1010 }
1011
1012 /**
1013 * Returns the given attributes from the parameters
1014 *
1015 * @param array $list List of attributes to get
1016 * @return array Attributes
1017 */
1018 public function getAttributes( array $list ) {
1019 static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
1020
1021 $ret = [];
1022 foreach ( $list as $key ) {
1023 if ( in_array( $key, $boolAttribs ) ) {
1024 if ( !empty( $this->mParams[$key] ) ) {
1025 $ret[$key] = '';
1026 }
1027 } elseif ( isset( $this->mParams[$key] ) ) {
1028 $ret[$key] = $this->mParams[$key];
1029 }
1030 }
1031
1032 return $ret;
1033 }
1034
1035 /**
1036 * Given an array of msg-key => value mappings, returns an array with keys
1037 * being the message texts. It also forces values to strings.
1038 *
1039 * @param array $options
1040 * @return array
1041 */
1042 private function lookupOptionsKeys( $options ) {
1043 $ret = [];
1044 foreach ( $options as $key => $value ) {
1045 $key = $this->msg( $key )->plain();
1046 $ret[$key] = is_array( $value )
1047 ? $this->lookupOptionsKeys( $value )
1048 : strval( $value );
1049 }
1050 return $ret;
1051 }
1052
1053 /**
1054 * Recursively forces values in an array to strings, because issues arise
1055 * with integer 0 as a value.
1056 *
1057 * @param array $array
1058 * @return array|string
1059 */
1060 public static function forceToStringRecursive( $array ) {
1061 if ( is_array( $array ) ) {
1062 return array_map( [ __CLASS__, 'forceToStringRecursive' ], $array );
1063 } else {
1064 return strval( $array );
1065 }
1066 }
1067
1068 /**
1069 * Fetch the array of options from the field's parameters. In order, this
1070 * checks 'options-messages', 'options', then 'options-message'.
1071 *
1072 * @return array|null Options array
1073 */
1074 public function getOptions() {
1075 if ( $this->mOptions === false ) {
1076 if ( array_key_exists( 'options-messages', $this->mParams ) ) {
1077 $this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'] );
1078 } elseif ( array_key_exists( 'options', $this->mParams ) ) {
1079 $this->mOptionsLabelsNotFromMessage = true;
1080 $this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
1081 } elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
1082 $message = $this->getMessage( $this->mParams['options-message'] )->inContentLanguage()->plain();
1083 $this->mOptions = Xml::listDropDownOptions( $message );
1084 } else {
1085 $this->mOptions = null;
1086 }
1087 }
1088
1089 return $this->mOptions;
1090 }
1091
1092 /**
1093 * Get options and make them into arrays suitable for OOUI.
1094 * @return array Options for inclusion in a select or whatever.
1095 */
1096 public function getOptionsOOUI() {
1097 $oldoptions = $this->getOptions();
1098
1099 if ( $oldoptions === null ) {
1100 return null;
1101 }
1102
1103 return Xml::listDropDownOptionsOoui( $oldoptions );
1104 }
1105
1106 /**
1107 * flatten an array of options to a single array, for instance,
1108 * a set of "<options>" inside "<optgroups>".
1109 *
1110 * @param array $options Associative Array with values either Strings or Arrays
1111 * @return array Flattened input
1112 */
1113 public static function flattenOptions( $options ) {
1114 $flatOpts = [];
1115
1116 foreach ( $options as $value ) {
1117 if ( is_array( $value ) ) {
1118 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1119 } else {
1120 $flatOpts[] = $value;
1121 }
1122 }
1123
1124 return $flatOpts;
1125 }
1126
1127 /**
1128 * Formats one or more errors as accepted by field validation-callback.
1129 *
1130 * @param string|Message|array $errors Array of strings or Message instances
1131 * @return string HTML
1132 * @since 1.18
1133 */
1134 protected static function formatErrors( $errors ) {
1135 // Note: If you change the logic in this method, change
1136 // htmlform.Checker.js to match.
1137
1138 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1139 $errors = array_shift( $errors );
1140 }
1141
1142 if ( is_array( $errors ) ) {
1143 $lines = [];
1144 foreach ( $errors as $error ) {
1145 if ( $error instanceof Message ) {
1146 $lines[] = Html::rawElement( 'li', [], $error->parse() );
1147 } else {
1148 $lines[] = Html::rawElement( 'li', [], $error );
1149 }
1150 }
1151
1152 return Html::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1153 } else {
1154 if ( $errors instanceof Message ) {
1155 $errors = $errors->parse();
1156 }
1157
1158 return Html::rawElement( 'span', [ 'class' => 'error' ], $errors );
1159 }
1160 }
1161
1162 /**
1163 * Turns a *-message parameter (which could be a MessageSpecifier, or a message name, or a
1164 * name + parameters array) into a Message.
1165 * @param mixed $value
1166 * @return Message
1167 */
1168 protected function getMessage( $value ) {
1169 $message = Message::newFromSpecifier( $value );
1170
1171 if ( $this->mParent ) {
1172 $message->setContext( $this->mParent );
1173 }
1174
1175 return $message;
1176 }
1177
1178 /**
1179 * Skip this field when collecting data.
1180 * @param WebRequest $request
1181 * @return bool
1182 * @since 1.27
1183 */
1184 public function skipLoadData( $request ) {
1185 return !empty( $this->mParams['nodata'] );
1186 }
1187
1188 /**
1189 * Whether this field requires the user agent to have JavaScript enabled for the client-side HTML5
1190 * form validation to work correctly.
1191 *
1192 * @return bool
1193 * @since 1.29
1194 */
1195 public function needsJSForHtml5FormValidation() {
1196 if ( $this->mHideIf ) {
1197 // This is probably more restrictive than it needs to be, but better safe than sorry
1198 return true;
1199 }
1200 return false;
1201 }
1202 }