Merge "resetUserEmail: Allow resetting email without scrambling password"
[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
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 !isset( $alldata[$tmp] ) &&
121 isset( $alldata[substr( $tmp, 2 )] )
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 ) || !isset( $data[$key] ) ) {
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 $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 $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 $msgInfo = $params['label-message'];
385
386 if ( is_array( $msgInfo ) ) {
387 $msg = array_shift( $msgInfo );
388 } else {
389 $msg = $msgInfo;
390 $msgInfo = [];
391 }
392
393 $this->mLabel = $this->msg( $msg, $msgInfo )->parse();
394 } elseif ( isset( $params['label'] ) ) {
395 if ( $params['label'] === '&#160;' ) {
396 // Apparently some things set &nbsp directly and in an odd format
397 $this->mLabel = '&#160;';
398 } else {
399 $this->mLabel = htmlspecialchars( $params['label'] );
400 }
401 } elseif ( isset( $params['label-raw'] ) ) {
402 $this->mLabel = $params['label-raw'];
403 }
404
405 $this->mName = "wp{$params['fieldname']}";
406 if ( isset( $params['name'] ) ) {
407 $this->mName = $params['name'];
408 }
409
410 if ( isset( $params['dir'] ) ) {
411 $this->mDir = $params['dir'];
412 }
413
414 $validName = Sanitizer::escapeId( $this->mName );
415 $validName = str_replace( [ '.5B', '.5D' ], [ '[', ']' ], $validName );
416 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
417 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
418 }
419
420 $this->mID = "mw-input-{$this->mName}";
421
422 if ( isset( $params['default'] ) ) {
423 $this->mDefault = $params['default'];
424 }
425
426 if ( isset( $params['id'] ) ) {
427 $id = $params['id'];
428 $validId = Sanitizer::escapeId( $id );
429
430 if ( $id != $validId ) {
431 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
432 }
433
434 $this->mID = $id;
435 }
436
437 if ( isset( $params['cssclass'] ) ) {
438 $this->mClass = $params['cssclass'];
439 }
440
441 if ( isset( $params['csshelpclass'] ) ) {
442 $this->mHelpClass = $params['csshelpclass'];
443 }
444
445 if ( isset( $params['validation-callback'] ) ) {
446 $this->mValidationCallback = $params['validation-callback'];
447 }
448
449 if ( isset( $params['filter-callback'] ) ) {
450 $this->mFilterCallback = $params['filter-callback'];
451 }
452
453 if ( isset( $params['flatlist'] ) ) {
454 $this->mClass .= ' mw-htmlform-flatlist';
455 }
456
457 if ( isset( $params['hidelabel'] ) ) {
458 $this->mShowEmptyLabels = false;
459 }
460
461 if ( isset( $params['hide-if'] ) ) {
462 $this->mHideIf = $params['hide-if'];
463 }
464 }
465
466 /**
467 * Get the complete table row for the input, including help text,
468 * labels, and whatever.
469 *
470 * @param string $value The value to set the input to.
471 *
472 * @return string Complete HTML table row.
473 */
474 function getTableRow( $value ) {
475 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
476 $inputHtml = $this->getInputHTML( $value );
477 $fieldType = get_class( $this );
478 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
479 $cellAttributes = [];
480 $rowAttributes = [];
481 $rowClasses = '';
482
483 if ( !empty( $this->mParams['vertical-label'] ) ) {
484 $cellAttributes['colspan'] = 2;
485 $verticalLabel = true;
486 } else {
487 $verticalLabel = false;
488 }
489
490 $label = $this->getLabelHtml( $cellAttributes );
491
492 $field = Html::rawElement(
493 'td',
494 [ 'class' => 'mw-input' ] + $cellAttributes,
495 $inputHtml . "\n$errors"
496 );
497
498 if ( $this->mHideIf ) {
499 $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
500 $rowClasses .= ' mw-htmlform-hide-if';
501 }
502
503 if ( $verticalLabel ) {
504 $html = Html::rawElement( 'tr',
505 $rowAttributes + [ 'class' => "mw-htmlform-vertical-label $rowClasses" ], $label );
506 $html .= Html::rawElement( 'tr',
507 $rowAttributes + [
508 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
509 ],
510 $field );
511 } else {
512 $html =
513 Html::rawElement( 'tr',
514 $rowAttributes + [
515 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
516 ],
517 $label . $field );
518 }
519
520 return $html . $helptext;
521 }
522
523 /**
524 * Get the complete div for the input, including help text,
525 * labels, and whatever.
526 * @since 1.20
527 *
528 * @param string $value The value to set the input to.
529 *
530 * @return string Complete HTML table row.
531 */
532 public function getDiv( $value ) {
533 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
534 $inputHtml = $this->getInputHTML( $value );
535 $fieldType = get_class( $this );
536 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
537 $cellAttributes = [];
538 $label = $this->getLabelHtml( $cellAttributes );
539
540 $outerDivClass = [
541 'mw-input',
542 'mw-htmlform-nolabel' => ( $label === '' )
543 ];
544
545 $horizontalLabel = isset( $this->mParams['horizontal-label'] )
546 ? $this->mParams['horizontal-label'] : false;
547
548 if ( $horizontalLabel ) {
549 $field = '&#160;' . $inputHtml . "\n$errors";
550 } else {
551 $field = Html::rawElement(
552 'div',
553 [ 'class' => $outerDivClass ] + $cellAttributes,
554 $inputHtml . "\n$errors"
555 );
556 }
557 $divCssClasses = [ "mw-htmlform-field-$fieldType",
558 $this->mClass, $this->mVFormClass, $errorClass ];
559
560 $wrapperAttributes = [
561 'class' => $divCssClasses,
562 ];
563 if ( $this->mHideIf ) {
564 $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
565 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
566 }
567 $html = Html::rawElement( 'div', $wrapperAttributes, $label . $field );
568 $html .= $helptext;
569
570 return $html;
571 }
572
573 /**
574 * Get the OOUI version of the div. Falls back to getDiv by default.
575 * @since 1.26
576 *
577 * @param string $value The value to set the input to.
578 *
579 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
580 */
581 public function getOOUI( $value ) {
582 $inputField = $this->getInputOOUI( $value );
583
584 if ( !$inputField ) {
585 // This field doesn't have an OOUI implementation yet at all. Fall back to getDiv() to
586 // generate the whole field, label and errors and all, then wrap it in a Widget.
587 // It might look weird, but it'll work OK.
588 return $this->getFieldLayoutOOUI(
589 new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $this->getDiv( $value ) ) ] ),
590 [ 'infusable' => false, 'align' => 'top' ]
591 );
592 }
593
594 $infusable = true;
595 if ( is_string( $inputField ) ) {
596 // We have an OOUI implementation, but it's not proper, and we got a load of HTML.
597 // Cheat a little and wrap it in a widget. It won't be infusable, though, since client-side
598 // JavaScript doesn't know how to rebuilt the contents.
599 $inputField = new OOUI\Widget( [ 'content' => new OOUI\HtmlSnippet( $inputField ) ] );
600 $infusable = false;
601 }
602
603 $fieldType = get_class( $this );
604 $helpText = $this->getHelpText();
605 $errors = $this->getErrorsRaw( $value );
606 foreach ( $errors as &$error ) {
607 $error = new OOUI\HtmlSnippet( $error );
608 }
609
610 $config = [
611 'classes' => [ "mw-htmlform-field-$fieldType", $this->mClass ],
612 'align' => $this->getLabelAlignOOUI(),
613 'help' => $helpText !== null ? new OOUI\HtmlSnippet( $helpText ) : null,
614 'errors' => $errors,
615 'infusable' => $infusable,
616 ];
617
618 // the element could specify, that the label doesn't need to be added
619 $label = $this->getLabel();
620 if ( $label ) {
621 $config['label'] = new OOUI\HtmlSnippet( $label );
622 }
623
624 return $this->getFieldLayoutOOUI( $inputField, $config );
625 }
626
627 /**
628 * Get label alignment when generating field for OOUI.
629 * @return string 'left', 'right', 'top' or 'inline'
630 */
631 protected function getLabelAlignOOUI() {
632 return 'top';
633 }
634
635 /**
636 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
637 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
638 */
639 protected function getFieldLayoutOOUI( $inputField, $config ) {
640 if ( isset( $this->mClassWithButton ) ) {
641 $buttonWidget = $this->mClassWithButton->getInputOOUI( '' );
642 return new OOUI\ActionFieldLayout( $inputField, $buttonWidget, $config );
643 }
644 return new OOUI\FieldLayout( $inputField, $config );
645 }
646
647 /**
648 * Get the complete raw fields for the input, including help text,
649 * labels, and whatever.
650 * @since 1.20
651 *
652 * @param string $value The value to set the input to.
653 *
654 * @return string Complete HTML table row.
655 */
656 public function getRaw( $value ) {
657 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
658 $inputHtml = $this->getInputHTML( $value );
659 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
660 $cellAttributes = [];
661 $label = $this->getLabelHtml( $cellAttributes );
662
663 $html = "\n$errors";
664 $html .= $label;
665 $html .= $inputHtml;
666 $html .= $helptext;
667
668 return $html;
669 }
670
671 /**
672 * Get the complete field for the input, including help text,
673 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
674 *
675 * @since 1.25
676 * @param string $value The value to set the input to.
677 * @return string Complete HTML field.
678 */
679 public function getVForm( $value ) {
680 // Ewwww
681 $this->mVFormClass = ' mw-ui-vform-field';
682 return $this->getDiv( $value );
683 }
684
685 /**
686 * Get the complete field as an inline element.
687 * @since 1.25
688 * @param string $value The value to set the input to.
689 * @return string Complete HTML inline element
690 */
691 public function getInline( $value ) {
692 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
693 $inputHtml = $this->getInputHTML( $value );
694 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
695 $cellAttributes = [];
696 $label = $this->getLabelHtml( $cellAttributes );
697
698 $html = "\n" . $errors .
699 $label . '&#160;' .
700 $inputHtml .
701 $helptext;
702
703 return $html;
704 }
705
706 /**
707 * Generate help text HTML in table format
708 * @since 1.20
709 *
710 * @param string|null $helptext
711 * @return string
712 */
713 public function getHelpTextHtmlTable( $helptext ) {
714 if ( is_null( $helptext ) ) {
715 return '';
716 }
717
718 $rowAttributes = [];
719 if ( $this->mHideIf ) {
720 $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
721 $rowAttributes['class'] = 'mw-htmlform-hide-if';
722 }
723
724 $tdClasses = [ 'htmlform-tip' ];
725 if ( $this->mHelpClass !== false ) {
726 $tdClasses[] = $this->mHelpClass;
727 }
728 $row = Html::rawElement( 'td', [ 'colspan' => 2, 'class' => $tdClasses ], $helptext );
729 $row = Html::rawElement( 'tr', $rowAttributes, $row );
730
731 return $row;
732 }
733
734 /**
735 * Generate help text HTML in div format
736 * @since 1.20
737 *
738 * @param string|null $helptext
739 *
740 * @return string
741 */
742 public function getHelpTextHtmlDiv( $helptext ) {
743 if ( is_null( $helptext ) ) {
744 return '';
745 }
746
747 $wrapperAttributes = [
748 'class' => 'htmlform-tip',
749 ];
750 if ( $this->mHelpClass !== false ) {
751 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
752 }
753 if ( $this->mHideIf ) {
754 $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
755 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
756 }
757 $div = Html::rawElement( 'div', $wrapperAttributes, $helptext );
758
759 return $div;
760 }
761
762 /**
763 * Generate help text HTML formatted for raw output
764 * @since 1.20
765 *
766 * @param string|null $helptext
767 * @return string
768 */
769 public function getHelpTextHtmlRaw( $helptext ) {
770 return $this->getHelpTextHtmlDiv( $helptext );
771 }
772
773 /**
774 * Determine the help text to display
775 * @since 1.20
776 * @return string HTML
777 */
778 public function getHelpText() {
779 $helptext = null;
780
781 if ( isset( $this->mParams['help-message'] ) ) {
782 $this->mParams['help-messages'] = [ $this->mParams['help-message'] ];
783 }
784
785 if ( isset( $this->mParams['help-messages'] ) ) {
786 foreach ( $this->mParams['help-messages'] as $name ) {
787 $helpMessage = (array)$name;
788 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
789
790 if ( $msg->exists() ) {
791 if ( is_null( $helptext ) ) {
792 $helptext = '';
793 } else {
794 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
795 }
796 $helptext .= $msg->parse(); // Append message
797 }
798 }
799 } elseif ( isset( $this->mParams['help'] ) ) {
800 $helptext = $this->mParams['help'];
801 }
802
803 return $helptext;
804 }
805
806 /**
807 * Determine form errors to display and their classes
808 * @since 1.20
809 *
810 * @param string $value The value of the input
811 * @return array array( $errors, $errorClass )
812 */
813 public function getErrorsAndErrorClass( $value ) {
814 $errors = $this->validate( $value, $this->mParent->mFieldData );
815
816 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
817 $errors = '';
818 $errorClass = '';
819 } else {
820 $errors = self::formatErrors( $errors );
821 $errorClass = 'mw-htmlform-invalid-input';
822 }
823
824 return [ $errors, $errorClass ];
825 }
826
827 /**
828 * Determine form errors to display, returning them in an array.
829 *
830 * @since 1.26
831 * @param string $value The value of the input
832 * @return string[] Array of error HTML strings
833 */
834 public function getErrorsRaw( $value ) {
835 $errors = $this->validate( $value, $this->mParent->mFieldData );
836
837 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
838 $errors = [];
839 }
840
841 if ( !is_array( $errors ) ) {
842 $errors = [ $errors ];
843 }
844 foreach ( $errors as &$error ) {
845 if ( $error instanceof Message ) {
846 $error = $error->parse();
847 }
848 }
849
850 return $errors;
851 }
852
853 /**
854 * @return string HTML
855 */
856 function getLabel() {
857 return is_null( $this->mLabel ) ? '' : $this->mLabel;
858 }
859
860 function getLabelHtml( $cellAttributes = [] ) {
861 # Don't output a for= attribute for labels with no associated input.
862 # Kind of hacky here, possibly we don't want these to be <label>s at all.
863 $for = [];
864
865 if ( $this->needsLabel() ) {
866 $for['for'] = $this->mID;
867 }
868
869 $labelValue = trim( $this->getLabel() );
870 $hasLabel = false;
871 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
872 $hasLabel = true;
873 }
874
875 $displayFormat = $this->mParent->getDisplayFormat();
876 $html = '';
877 $horizontalLabel = isset( $this->mParams['horizontal-label'] )
878 ? $this->mParams['horizontal-label'] : false;
879
880 if ( $displayFormat === 'table' ) {
881 $html =
882 Html::rawElement( 'td',
883 [ 'class' => 'mw-label' ] + $cellAttributes,
884 Html::rawElement( 'label', $for, $labelValue ) );
885 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
886 if ( $displayFormat === 'div' && !$horizontalLabel ) {
887 $html =
888 Html::rawElement( 'div',
889 [ 'class' => 'mw-label' ] + $cellAttributes,
890 Html::rawElement( 'label', $for, $labelValue ) );
891 } else {
892 $html = Html::rawElement( 'label', $for, $labelValue );
893 }
894 }
895
896 return $html;
897 }
898
899 function getDefault() {
900 if ( isset( $this->mDefault ) ) {
901 return $this->mDefault;
902 } else {
903 return null;
904 }
905 }
906
907 /**
908 * Returns the attributes required for the tooltip and accesskey.
909 *
910 * @return array Attributes
911 */
912 public function getTooltipAndAccessKey() {
913 if ( empty( $this->mParams['tooltip'] ) ) {
914 return [];
915 }
916
917 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
918 }
919
920 /**
921 * Returns the given attributes from the parameters
922 *
923 * @param array $list List of attributes to get
924 * @return array Attributes
925 */
926 public function getAttributes( array $list ) {
927 static $boolAttribs = [ 'disabled', 'required', 'autofocus', 'multiple', 'readonly' ];
928
929 $ret = [];
930 foreach ( $list as $key ) {
931 if ( in_array( $key, $boolAttribs ) ) {
932 if ( !empty( $this->mParams[$key] ) ) {
933 $ret[$key] = '';
934 }
935 } elseif ( isset( $this->mParams[$key] ) ) {
936 $ret[$key] = $this->mParams[$key];
937 }
938 }
939
940 return $ret;
941 }
942
943 /**
944 * Given an array of msg-key => value mappings, returns an array with keys
945 * being the message texts. It also forces values to strings.
946 *
947 * @param array $options
948 * @return array
949 */
950 private function lookupOptionsKeys( $options ) {
951 $ret = [];
952 foreach ( $options as $key => $value ) {
953 $key = $this->msg( $key )->plain();
954 $ret[$key] = is_array( $value )
955 ? $this->lookupOptionsKeys( $value )
956 : strval( $value );
957 }
958 return $ret;
959 }
960
961 /**
962 * Recursively forces values in an array to strings, because issues arise
963 * with integer 0 as a value.
964 *
965 * @param array $array
966 * @return array
967 */
968 static function forceToStringRecursive( $array ) {
969 if ( is_array( $array ) ) {
970 return array_map( [ __CLASS__, 'forceToStringRecursive' ], $array );
971 } else {
972 return strval( $array );
973 }
974 }
975
976 /**
977 * Fetch the array of options from the field's parameters. In order, this
978 * checks 'options-messages', 'options', then 'options-message'.
979 *
980 * @return array|null Options array
981 */
982 public function getOptions() {
983 if ( $this->mOptions === false ) {
984 if ( array_key_exists( 'options-messages', $this->mParams ) ) {
985 $this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'] );
986 } elseif ( array_key_exists( 'options', $this->mParams ) ) {
987 $this->mOptionsLabelsNotFromMessage = true;
988 $this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
989 } elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
990 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
991 $message = $this->msg( $this->mParams['options-message'] )->inContentLanguage()->plain();
992
993 $optgroup = false;
994 $this->mOptions = [];
995 foreach ( explode( "\n", $message ) as $option ) {
996 $value = trim( $option );
997 if ( $value == '' ) {
998 continue;
999 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1000 # A new group is starting...
1001 $value = trim( substr( $value, 1 ) );
1002 $optgroup = $value;
1003 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1004 # groupmember
1005 $opt = trim( substr( $value, 2 ) );
1006 if ( $optgroup === false ) {
1007 $this->mOptions[$opt] = $opt;
1008 } else {
1009 $this->mOptions[$optgroup][$opt] = $opt;
1010 }
1011 } else {
1012 # groupless reason list
1013 $optgroup = false;
1014 $this->mOptions[$option] = $option;
1015 }
1016 }
1017 } else {
1018 $this->mOptions = null;
1019 }
1020 }
1021
1022 return $this->mOptions;
1023 }
1024
1025 /**
1026 * Get options and make them into arrays suitable for OOUI.
1027 * @return array Options for inclusion in a select or whatever.
1028 */
1029 public function getOptionsOOUI() {
1030 $oldoptions = $this->getOptions();
1031
1032 if ( $oldoptions === null ) {
1033 return null;
1034 }
1035
1036 $options = [];
1037
1038 foreach ( $oldoptions as $text => $data ) {
1039 $options[] = [
1040 'data' => (string)$data,
1041 'label' => (string)$text,
1042 ];
1043 }
1044
1045 return $options;
1046 }
1047
1048 /**
1049 * flatten an array of options to a single array, for instance,
1050 * a set of "<options>" inside "<optgroups>".
1051 *
1052 * @param array $options Associative Array with values either Strings or Arrays
1053 * @return array Flattened input
1054 */
1055 public static function flattenOptions( $options ) {
1056 $flatOpts = [];
1057
1058 foreach ( $options as $value ) {
1059 if ( is_array( $value ) ) {
1060 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1061 } else {
1062 $flatOpts[] = $value;
1063 }
1064 }
1065
1066 return $flatOpts;
1067 }
1068
1069 /**
1070 * Formats one or more errors as accepted by field validation-callback.
1071 *
1072 * @param string|Message|array $errors Array of strings or Message instances
1073 * @return string HTML
1074 * @since 1.18
1075 */
1076 protected static function formatErrors( $errors ) {
1077 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1078 $errors = array_shift( $errors );
1079 }
1080
1081 if ( is_array( $errors ) ) {
1082 $lines = [];
1083 foreach ( $errors as $error ) {
1084 if ( $error instanceof Message ) {
1085 $lines[] = Html::rawElement( 'li', [], $error->parse() );
1086 } else {
1087 $lines[] = Html::rawElement( 'li', [], $error );
1088 }
1089 }
1090
1091 return Html::rawElement( 'ul', [ 'class' => 'error' ], implode( "\n", $lines ) );
1092 } else {
1093 if ( $errors instanceof Message ) {
1094 $errors = $errors->parse();
1095 }
1096
1097 return Html::rawElement( 'span', [ 'class' => 'error' ], $errors );
1098 }
1099 }
1100 }