Merge "Import: Handle uploads with sha1 starting with 0 properly"
[mediawiki.git] / includes / htmlform / HTMLFormField.php
blob3d9ec1f51fdf3674eba566259ea6b036ddc19fac
1 <?php
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;
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;
24 /**
25 * @var bool If true will generate an empty div element with no label
26 * @since 1.22
28 protected $mShowEmptyLabels = true;
30 /**
31 * @var HTMLForm
33 public $mParent;
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.
40 * @param string $value The value to set the input to; eg a default
41 * text for a text input.
43 * @return string Valid HTML.
45 abstract function getInputHTML( $value );
47 /**
48 * Same as getInputHTML, but returns an OOUI object.
49 * Defaults to false, which getOOUI will interpret as "use the HTML version"
51 * @param string $value
52 * @return OOUI\Widget|false
54 function getInputOOUI( $value ) {
55 return false;
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
63 public function canDisplayErrors() {
64 return true;
67 /**
68 * Get a translated interface message
70 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
71 * and wfMessage() otherwise.
73 * Parameters are the same as wfMessage().
75 * @return Message
77 function msg() {
78 $args = func_get_args();
80 if ( $this->mParent ) {
81 $callback = array( $this->mParent, 'msg' );
82 } else {
83 $callback = 'wfMessage';
86 return call_user_func_array( $callback, $args );
89 /**
90 * If this field has a user-visible output or not. If not,
91 * it will not be rendered
93 * @return bool
95 public function hasVisibleOutput() {
96 return true;
99 /**
100 * Fetch a field value from $alldata for the closest field matching a given
101 * name.
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.
108 * @param array $alldata
109 * @param string $name
110 * @return string
112 protected function getNearestFieldByName( $alldata, $name ) {
113 $tmp = $this->mName;
114 $thisKeys = array();
115 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
116 array_unshift( $thisKeys, $m[2] );
117 $tmp = $m[1];
119 if ( substr( $tmp, 0, 2 ) == 'wp' &&
120 !isset( $alldata[$tmp] ) &&
121 isset( $alldata[substr( $tmp, 2 )] )
123 // Adjust for name mangling.
124 $tmp = substr( $tmp, 2 );
126 array_unshift( $thisKeys, $tmp );
128 $tmp = $name;
129 $nameKeys = array();
130 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
131 array_unshift( $nameKeys, $m[2] );
132 $tmp = $m[1];
134 array_unshift( $nameKeys, $tmp );
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;
145 $data = $data[$key];
147 $testValue = (string)$data;
148 break;
151 return $testValue;
155 * Helper function for isHidden to handle recursive data structures.
157 * @param array $alldata
158 * @param array $params
159 * @return bool
160 * @throws MWException
162 protected function isHiddenRecurse( array $alldata, array $params ) {
163 $origParams = $params;
164 $op = array_shift( $params );
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"
175 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
176 return false;
179 return true;
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"
188 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
189 return true;
192 return false;
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"
201 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
202 return true;
205 return false;
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"
214 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
215 return false;
218 return true;
220 case 'NOT':
221 if ( count( $params ) !== 1 ) {
222 throw new MWException( "NOT takes exactly one parameter" );
224 $p = $params[0];
225 if ( !is_array( $p ) ) {
226 throw new MWException(
227 "Expected array, found " . gettype( $p ) . " at index 0"
230 return !$this->isHiddenRecurse( $alldata, $p );
232 case '===':
233 case '!==':
234 if ( count( $params ) !== 2 ) {
235 throw new MWException( "$op takes exactly two parameters" );
237 list( $field, $value ) = $params;
238 if ( !is_string( $field ) || !is_string( $value ) ) {
239 throw new MWException( "Parameters for $op must be strings" );
241 $testValue = $this->getNearestFieldByName( $alldata, $field );
242 switch ( $op ) {
243 case '===':
244 return ( $value === $testValue );
245 case '!==':
246 return ( $value !== $testValue );
249 default:
250 throw new MWException( "Unknown operation" );
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
262 * Test whether this field is supposed to be hidden, based on the values of
263 * the other form fields.
265 * @since 1.23
266 * @param array $alldata The data collected from the form
267 * @return bool
269 function isHidden( $alldata ) {
270 if ( !$this->mHideIf ) {
271 return false;
274 return $this->isHiddenRecurse( $alldata, $this->mHideIf );
278 * Override this function if the control can somehow trigger a form
279 * submission that shouldn't actually submit the HTMLForm.
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
285 * @return bool True to cancel the submission
287 function cancelSubmit( $value, $alldata ) {
288 return false;
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
296 * @param string|array $value The value the field was submitted with
297 * @param array $alldata The data collected from the form
299 * @return bool|string True on success, or String error to display, or
300 * false to fail validation without displaying an error.
302 function validate( $value, $alldata ) {
303 if ( $this->isHidden( $alldata ) ) {
304 return true;
307 if ( isset( $this->mParams['required'] )
308 && $this->mParams['required'] !== false
309 && $value === ''
311 return $this->msg( 'htmlform-required' )->parse();
314 if ( isset( $this->mValidationCallback ) ) {
315 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
318 return true;
321 function filter( $value, $alldata ) {
322 if ( isset( $this->mFilterCallback ) ) {
323 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
326 return $value;
330 * Should this field have a label, or is there no input element with the
331 * appropriate id for the label to point to?
333 * @return bool True to output a label, false to suppress
335 protected function needsLabel() {
336 return true;
340 * Tell the field whether to generate a separate label element if its label
341 * is blank.
343 * @since 1.22
345 * @param bool $show Set to false to not generate a label.
346 * @return void
348 public function setShowEmptyLabel( $show ) {
349 $this->mShowEmptyLabels = $show;
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.
356 * @param WebRequest $request
357 * @return string The value
359 function loadDataFromRequest( $request ) {
360 if ( $request->getCheck( $this->mName ) ) {
361 return $request->getText( $this->mName );
362 } else {
363 return $this->getDefault();
368 * Initialise the object
370 * @param array $params Associative Array. See HTMLForm doc for syntax.
372 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
373 * @throws MWException
375 function __construct( $params ) {
376 $this->mParams = $params;
378 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm ) {
379 $this->mParent = $params['parent'];
382 # Generate the label from a message, if possible
383 if ( isset( $params['label-message'] ) ) {
384 $msgInfo = $params['label-message'];
386 if ( is_array( $msgInfo ) ) {
387 $msg = array_shift( $msgInfo );
388 } else {
389 $msg = $msgInfo;
390 $msgInfo = array();
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'] );
401 } elseif ( isset( $params['label-raw'] ) ) {
402 $this->mLabel = $params['label-raw'];
405 $this->mName = "wp{$params['fieldname']}";
406 if ( isset( $params['name'] ) ) {
407 $this->mName = $params['name'];
410 if ( isset( $params['dir'] ) ) {
411 $this->mDir = $params['dir'];
414 $validName = Sanitizer::escapeId( $this->mName );
415 $validName = str_replace( array( '.5B', '.5D' ), array( '[', ']' ), $validName );
416 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
417 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
420 $this->mID = "mw-input-{$this->mName}";
422 if ( isset( $params['default'] ) ) {
423 $this->mDefault = $params['default'];
426 if ( isset( $params['id'] ) ) {
427 $id = $params['id'];
428 $validId = Sanitizer::escapeId( $id );
430 if ( $id != $validId ) {
431 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
434 $this->mID = $id;
437 if ( isset( $params['cssclass'] ) ) {
438 $this->mClass = $params['cssclass'];
441 if ( isset( $params['csshelpclass'] ) ) {
442 $this->mHelpClass = $params['csshelpclass'];
445 if ( isset( $params['validation-callback'] ) ) {
446 $this->mValidationCallback = $params['validation-callback'];
449 if ( isset( $params['filter-callback'] ) ) {
450 $this->mFilterCallback = $params['filter-callback'];
453 if ( isset( $params['flatlist'] ) ) {
454 $this->mClass .= ' mw-htmlform-flatlist';
457 if ( isset( $params['hidelabel'] ) ) {
458 $this->mShowEmptyLabels = false;
461 if ( isset( $params['hide-if'] ) ) {
462 $this->mHideIf = $params['hide-if'];
467 * Get the complete table row for the input, including help text,
468 * labels, and whatever.
470 * @param string $value The value to set the input to.
472 * @return string Complete HTML table row.
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 = array();
480 $rowAttributes = array();
481 $rowClasses = '';
483 if ( !empty( $this->mParams['vertical-label'] ) ) {
484 $cellAttributes['colspan'] = 2;
485 $verticalLabel = true;
486 } else {
487 $verticalLabel = false;
490 $label = $this->getLabelHtml( $cellAttributes );
492 $field = Html::rawElement(
493 'td',
494 array( 'class' => 'mw-input' ) + $cellAttributes,
495 $inputHtml . "\n$errors"
498 if ( $this->mHideIf ) {
499 $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
500 $rowClasses .= ' mw-htmlform-hide-if';
503 if ( $verticalLabel ) {
504 $html = Html::rawElement( 'tr',
505 $rowAttributes + array( 'class' => "mw-htmlform-vertical-label $rowClasses" ), $label );
506 $html .= Html::rawElement( 'tr',
507 $rowAttributes + array(
508 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
510 $field );
511 } else {
512 $html =
513 Html::rawElement( 'tr',
514 $rowAttributes + array(
515 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
517 $label . $field );
520 return $html . $helptext;
524 * Get the complete div for the input, including help text,
525 * labels, and whatever.
526 * @since 1.20
528 * @param string $value The value to set the input to.
530 * @return string Complete HTML table row.
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 = array();
538 $label = $this->getLabelHtml( $cellAttributes );
540 $outerDivClass = array(
541 'mw-input',
542 'mw-htmlform-nolabel' => ( $label === '' )
545 $horizontalLabel = isset( $this->mParams['horizontal-label'] )
546 ? $this->mParams['horizontal-label'] : false;
548 if ( $horizontalLabel ) {
549 $field = '&#160;' . $inputHtml . "\n$errors";
550 } else {
551 $field = Html::rawElement(
552 'div',
553 array( 'class' => $outerDivClass ) + $cellAttributes,
554 $inputHtml . "\n$errors"
557 $divCssClasses = array( "mw-htmlform-field-$fieldType",
558 $this->mClass, $this->mVFormClass, $errorClass );
560 $wrapperAttributes = array(
561 'class' => $divCssClasses,
563 if ( $this->mHideIf ) {
564 $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
565 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
567 $html = Html::rawElement( 'div', $wrapperAttributes, $label . $field );
568 $html .= $helptext;
570 return $html;
574 * Get the OOUI version of the div. Falls back to getDiv by default.
575 * @since 1.26
577 * @param string $value The value to set the input to.
579 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
581 public function getOOUI( $value ) {
582 $inputField = $this->getInputOOUI( $value );
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( array( 'content' => new OOUI\HtmlSnippet( $this->getDiv( $value ) ) ) ),
590 array( 'infusable' => false )
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( array( 'content' => new OOUI\HtmlSnippet( $inputField ) ) );
600 $infusable = false;
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 );
610 $config = array(
611 'classes' => array( "mw-htmlform-field-$fieldType", $this->mClass ),
612 'align' => $this->getLabelAlignOOUI(),
613 'label' => new OOUI\HtmlSnippet( $this->getLabel() ),
614 'help' => $helpText !== null ? new OOUI\HtmlSnippet( $helpText ) : null,
615 'errors' => $errors,
616 'infusable' => $infusable,
619 return $this->getFieldLayoutOOUI( $inputField, $config );
623 * Get label alignment when generating field for OOUI.
624 * @return string 'left', 'right', 'top' or 'inline'
626 protected function getLabelAlignOOUI() {
627 return 'top';
631 * Get a FieldLayout (or subclass thereof) to wrap this field in when using OOUI output.
632 * @return OOUI\FieldLayout|OOUI\ActionFieldLayout
634 protected function getFieldLayoutOOUI( $inputField, $config ) {
635 if ( isset( $this->mClassWithButton ) ) {
636 $buttonWidget = $this->mClassWithButton->getInputOOUI( '' );
637 return new OOUI\ActionFieldLayout( $inputField, $buttonWidget, $config );
639 return new OOUI\FieldLayout( $inputField, $config );
643 * Get the complete raw fields for the input, including help text,
644 * labels, and whatever.
645 * @since 1.20
647 * @param string $value The value to set the input to.
649 * @return string Complete HTML table row.
651 public function getRaw( $value ) {
652 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
653 $inputHtml = $this->getInputHTML( $value );
654 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
655 $cellAttributes = array();
656 $label = $this->getLabelHtml( $cellAttributes );
658 $html = "\n$errors";
659 $html .= $label;
660 $html .= $inputHtml;
661 $html .= $helptext;
663 return $html;
667 * Get the complete field for the input, including help text,
668 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
670 * @since 1.25
671 * @param string $value The value to set the input to.
672 * @return string Complete HTML field.
674 public function getVForm( $value ) {
675 // Ewwww
676 $this->mVFormClass = ' mw-ui-vform-field';
677 return $this->getDiv( $value );
681 * Get the complete field as an inline element.
682 * @since 1.25
683 * @param string $value The value to set the input to.
684 * @return string Complete HTML inline element
686 public function getInline( $value ) {
687 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
688 $inputHtml = $this->getInputHTML( $value );
689 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
690 $cellAttributes = array();
691 $label = $this->getLabelHtml( $cellAttributes );
693 $html = "\n" . $errors .
694 $label . '&#160;' .
695 $inputHtml .
696 $helptext;
698 return $html;
702 * Generate help text HTML in table format
703 * @since 1.20
705 * @param string|null $helptext
706 * @return string
708 public function getHelpTextHtmlTable( $helptext ) {
709 if ( is_null( $helptext ) ) {
710 return '';
713 $rowAttributes = array();
714 if ( $this->mHideIf ) {
715 $rowAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
716 $rowAttributes['class'] = 'mw-htmlform-hide-if';
719 $tdClasses = array( 'htmlform-tip' );
720 if ( $this->mHelpClass !== false ) {
721 $tdClasses[] = $this->mHelpClass;
723 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => $tdClasses ), $helptext );
724 $row = Html::rawElement( 'tr', $rowAttributes, $row );
726 return $row;
730 * Generate help text HTML in div format
731 * @since 1.20
733 * @param string|null $helptext
735 * @return string
737 public function getHelpTextHtmlDiv( $helptext ) {
738 if ( is_null( $helptext ) ) {
739 return '';
742 $wrapperAttributes = array(
743 'class' => 'htmlform-tip',
745 if ( $this->mHelpClass !== false ) {
746 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
748 if ( $this->mHideIf ) {
749 $wrapperAttributes['data-hide-if'] = FormatJson::encode( $this->mHideIf );
750 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
752 $div = Html::rawElement( 'div', $wrapperAttributes, $helptext );
754 return $div;
758 * Generate help text HTML formatted for raw output
759 * @since 1.20
761 * @param string|null $helptext
762 * @return string
764 public function getHelpTextHtmlRaw( $helptext ) {
765 return $this->getHelpTextHtmlDiv( $helptext );
769 * Determine the help text to display
770 * @since 1.20
771 * @return string HTML
773 public function getHelpText() {
774 $helptext = null;
776 if ( isset( $this->mParams['help-message'] ) ) {
777 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
780 if ( isset( $this->mParams['help-messages'] ) ) {
781 foreach ( $this->mParams['help-messages'] as $name ) {
782 $helpMessage = (array)$name;
783 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
785 if ( $msg->exists() ) {
786 if ( is_null( $helptext ) ) {
787 $helptext = '';
788 } else {
789 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
791 $helptext .= $msg->parse(); // Append message
794 } elseif ( isset( $this->mParams['help'] ) ) {
795 $helptext = $this->mParams['help'];
798 return $helptext;
802 * Determine form errors to display and their classes
803 * @since 1.20
805 * @param string $value The value of the input
806 * @return array array( $errors, $errorClass )
808 public function getErrorsAndErrorClass( $value ) {
809 $errors = $this->validate( $value, $this->mParent->mFieldData );
811 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
812 $errors = '';
813 $errorClass = '';
814 } else {
815 $errors = self::formatErrors( $errors );
816 $errorClass = 'mw-htmlform-invalid-input';
819 return array( $errors, $errorClass );
823 * Determine form errors to display, returning them in an array.
825 * @since 1.26
826 * @param string $value The value of the input
827 * @return string[] Array of error HTML strings
829 public function getErrorsRaw( $value ) {
830 $errors = $this->validate( $value, $this->mParent->mFieldData );
832 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
833 $errors = array();
836 if ( !is_array( $errors ) ) {
837 $errors = array( $errors );
839 foreach ( $errors as &$error ) {
840 if ( $error instanceof Message ) {
841 $error = $error->parse();
845 return $errors;
849 * @return string HTML
851 function getLabel() {
852 return is_null( $this->mLabel ) ? '' : $this->mLabel;
855 function getLabelHtml( $cellAttributes = array() ) {
856 # Don't output a for= attribute for labels with no associated input.
857 # Kind of hacky here, possibly we don't want these to be <label>s at all.
858 $for = array();
860 if ( $this->needsLabel() ) {
861 $for['for'] = $this->mID;
864 $labelValue = trim( $this->getLabel() );
865 $hasLabel = false;
866 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
867 $hasLabel = true;
870 $displayFormat = $this->mParent->getDisplayFormat();
871 $html = '';
872 $horizontalLabel = isset( $this->mParams['horizontal-label'] )
873 ? $this->mParams['horizontal-label'] : false;
875 if ( $displayFormat === 'table' ) {
876 $html =
877 Html::rawElement( 'td',
878 array( 'class' => 'mw-label' ) + $cellAttributes,
879 Html::rawElement( 'label', $for, $labelValue ) );
880 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
881 if ( $displayFormat === 'div' && !$horizontalLabel ) {
882 $html =
883 Html::rawElement( 'div',
884 array( 'class' => 'mw-label' ) + $cellAttributes,
885 Html::rawElement( 'label', $for, $labelValue ) );
886 } else {
887 $html = Html::rawElement( 'label', $for, $labelValue );
891 return $html;
894 function getDefault() {
895 if ( isset( $this->mDefault ) ) {
896 return $this->mDefault;
897 } else {
898 return null;
903 * Returns the attributes required for the tooltip and accesskey.
905 * @return array Attributes
907 public function getTooltipAndAccessKey() {
908 if ( empty( $this->mParams['tooltip'] ) ) {
909 return array();
912 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
916 * Get a translated key if necessary.
917 * @param array|null $mappings Array of mappings, 'original' => 'translated'
918 * @param string $key
919 * @return string
921 protected function getMappedKey( $mappings, $key ) {
922 if ( !is_array( $mappings ) ) {
923 return $key;
926 if ( !empty( $mappings[$key] ) ) {
927 return $mappings[$key];
930 return $key;
934 * Returns the given attributes from the parameters
936 * @param array $list List of attributes to get
937 * @param array $mappings Optional - Key/value map of attribute names to use
938 * instead of the ones passed in.
939 * @return array Attributes
941 public function getAttributes( array $list, array $mappings = null ) {
942 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
944 $ret = array();
945 foreach ( $list as $key ) {
946 $mappedKey = $this->getMappedKey( $mappings, $key );
948 if ( in_array( $key, $boolAttribs ) ) {
949 if ( !empty( $this->mParams[$key] ) ) {
950 $ret[$mappedKey] = $mappedKey;
952 } elseif ( isset( $this->mParams[$key] ) ) {
953 $ret[$mappedKey] = $this->mParams[$key];
957 return $ret;
961 * Given an array of msg-key => value mappings, returns an array with keys
962 * being the message texts. It also forces values to strings.
964 * @param array $options
965 * @return array
967 private function lookupOptionsKeys( $options ) {
968 $ret = array();
969 foreach ( $options as $key => $value ) {
970 $key = $this->msg( $key )->plain();
971 $ret[$key] = is_array( $value )
972 ? $this->lookupOptionsKeys( $value )
973 : strval( $value );
975 return $ret;
979 * Recursively forces values in an array to strings, because issues arise
980 * with integer 0 as a value.
982 * @param array $array
983 * @return array
985 static function forceToStringRecursive( $array ) {
986 if ( is_array( $array ) ) {
987 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
988 } else {
989 return strval( $array );
994 * Fetch the array of options from the field's parameters. In order, this
995 * checks 'options-messages', 'options', then 'options-message'.
997 * @return array|null Options array
999 public function getOptions() {
1000 if ( $this->mOptions === false ) {
1001 if ( array_key_exists( 'options-messages', $this->mParams ) ) {
1002 $this->mOptions = $this->lookupOptionsKeys( $this->mParams['options-messages'] );
1003 } elseif ( array_key_exists( 'options', $this->mParams ) ) {
1004 $this->mOptionsLabelsNotFromMessage = true;
1005 $this->mOptions = self::forceToStringRecursive( $this->mParams['options'] );
1006 } elseif ( array_key_exists( 'options-message', $this->mParams ) ) {
1007 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
1008 $message = $this->msg( $this->mParams['options-message'] )->inContentLanguage()->plain();
1010 $optgroup = false;
1011 $this->mOptions = array();
1012 foreach ( explode( "\n", $message ) as $option ) {
1013 $value = trim( $option );
1014 if ( $value == '' ) {
1015 continue;
1016 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1017 # A new group is starting...
1018 $value = trim( substr( $value, 1 ) );
1019 $optgroup = $value;
1020 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1021 # groupmember
1022 $opt = trim( substr( $value, 2 ) );
1023 if ( $optgroup === false ) {
1024 $this->mOptions[$opt] = $opt;
1025 } else {
1026 $this->mOptions[$optgroup][$opt] = $opt;
1028 } else {
1029 # groupless reason list
1030 $optgroup = false;
1031 $this->mOptions[$option] = $option;
1034 } else {
1035 $this->mOptions = null;
1039 return $this->mOptions;
1043 * Get options and make them into arrays suitable for OOUI.
1044 * @return array Options for inclusion in a select or whatever.
1046 public function getOptionsOOUI() {
1047 $oldoptions = $this->getOptions();
1049 if ( $oldoptions === null ) {
1050 return null;
1053 $options = array();
1055 foreach ( $oldoptions as $text => $data ) {
1056 $options[] = array(
1057 'data' => (string)$data,
1058 'label' => (string)$text,
1062 return $options;
1066 * flatten an array of options to a single array, for instance,
1067 * a set of "<options>" inside "<optgroups>".
1069 * @param array $options Associative Array with values either Strings or Arrays
1070 * @return array Flattened input
1072 public static function flattenOptions( $options ) {
1073 $flatOpts = array();
1075 foreach ( $options as $value ) {
1076 if ( is_array( $value ) ) {
1077 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1078 } else {
1079 $flatOpts[] = $value;
1083 return $flatOpts;
1087 * Formats one or more errors as accepted by field validation-callback.
1089 * @param string|Message|array $errors Array of strings or Message instances
1090 * @return string HTML
1091 * @since 1.18
1093 protected static function formatErrors( $errors ) {
1094 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1095 $errors = array_shift( $errors );
1098 if ( is_array( $errors ) ) {
1099 $lines = array();
1100 foreach ( $errors as $error ) {
1101 if ( $error instanceof Message ) {
1102 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1103 } else {
1104 $lines[] = Html::rawElement( 'li', array(), $error );
1108 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1109 } else {
1110 if ( $errors instanceof Message ) {
1111 $errors = $errors->parse();
1114 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );