4 * The parent class to generate form fields. Any field type should
5 * be a subclass of this.
7 abstract class HTMLFormField
{
10 protected $mValidationCallback;
11 protected $mFilterCallback;
14 protected $mLabel; # String label. Set on construction
16 protected $mClass = '';
17 protected $mVFormClass = '';
18 protected $mHelpClass = false;
20 protected $mOptions = false;
21 protected $mOptionsLabelsNotFromMessage = false;
22 protected $mHideIf = null;
25 * @var bool If true will generate an empty div element with no label
28 protected $mShowEmptyLabels = true;
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 );
48 * Get a translated interface message
50 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
51 * and wfMessage() otherwise.
53 * Parameters are the same as wfMessage().
58 $args = func_get_args();
60 if ( $this->mParent
) {
61 $callback = array( $this->mParent
, 'msg' );
63 $callback = 'wfMessage';
66 return call_user_func_array( $callback, $args );
71 * Fetch a field value from $alldata for the closest field matching a given
74 * This is complex because it needs to handle array fields like the user
75 * would expect. The general algorithm is to look for $name as a sibling
76 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
77 * that $name itself might be referencing an array.
79 * @param array $alldata
83 protected function getNearestFieldByName( $alldata, $name ) {
86 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
87 array_unshift( $thisKeys, $m[2] );
90 if ( substr( $tmp, 0, 2 ) == 'wp' &&
91 !isset( $alldata[$tmp] ) &&
92 isset( $alldata[substr( $tmp, 2 )] )
94 // Adjust for name mangling.
95 $tmp = substr( $tmp, 2 );
97 array_unshift( $thisKeys, $tmp );
101 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
102 array_unshift( $nameKeys, $m[2] );
105 array_unshift( $nameKeys, $tmp );
108 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
109 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
112 $key = array_shift( $keys );
113 if ( !is_array( $data ) ||
!isset( $data[$key] ) ) {
118 $testValue = (string)$data;
126 * Helper function for isHidden to handle recursive data structures.
128 * @param array $alldata
129 * @param array $params
131 * @throws MWException
133 protected function isHiddenRecurse( array $alldata, array $params ) {
134 $origParams = $params;
135 $op = array_shift( $params );
140 foreach ( $params as $i => $p ) {
141 if ( !is_array( $p ) ) {
142 throw new MWException(
143 "Expected array, found " . gettype( $p ) . " at index $i"
146 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
153 foreach ( $params as $p ) {
154 if ( !is_array( $p ) ) {
155 throw new MWException(
156 "Expected array, found " . gettype( $p ) . " at index $i"
159 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
166 foreach ( $params as $i => $p ) {
167 if ( !is_array( $p ) ) {
168 throw new MWException(
169 "Expected array, found " . gettype( $p ) . " at index $i"
172 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
179 foreach ( $params as $p ) {
180 if ( !is_array( $p ) ) {
181 throw new MWException(
182 "Expected array, found " . gettype( $p ) . " at index $i"
185 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
192 if ( count( $params ) !== 1 ) {
193 throw new MWException( "NOT takes exactly one parameter" );
196 if ( !is_array( $p ) ) {
197 throw new MWException(
198 "Expected array, found " . gettype( $p ) . " at index 0"
201 return !$this->isHiddenRecurse( $alldata, $p );
205 if ( count( $params ) !== 2 ) {
206 throw new MWException( "$op takes exactly two parameters" );
208 list( $field, $value ) = $params;
209 if ( !is_string( $field ) ||
!is_string( $value ) ) {
210 throw new MWException( "Parameters for $op must be strings" );
212 $testValue = $this->getNearestFieldByName( $alldata, $field );
215 return ( $value === $testValue );
217 return ( $value !== $testValue );
221 throw new MWException( "Unknown operation" );
223 } catch ( Exception
$ex ) {
224 throw new MWException(
225 "Invalid hide-if specification for $this->mName: " .
226 $ex->getMessage() . " in " . var_export( $origParams, true ),
233 * Test whether this field is supposed to be hidden, based on the values of
234 * the other form fields.
237 * @param array $alldata The data collected from the form
240 function isHidden( $alldata ) {
241 if ( !$this->mHideIf
) {
245 return $this->isHiddenRecurse( $alldata, $this->mHideIf
);
249 * Override this function if the control can somehow trigger a form
250 * submission that shouldn't actually submit the HTMLForm.
253 * @param string|array $value The value the field was submitted with
254 * @param array $alldata The data collected from the form
256 * @return bool True to cancel the submission
258 function cancelSubmit( $value, $alldata ) {
263 * Override this function to add specific validation checks on the
264 * field input. Don't forget to call parent::validate() to ensure
265 * that the user-defined callback mValidationCallback is still run
267 * @param string|array $value The value the field was submitted with
268 * @param array $alldata The data collected from the form
270 * @return bool|string True on success, or String error to display, or
271 * false to fail validation without displaying an error.
273 function validate( $value, $alldata ) {
274 if ( $this->isHidden( $alldata ) ) {
278 if ( isset( $this->mParams
['required'] )
279 && $this->mParams
['required'] !== false
282 return $this->msg( 'htmlform-required' )->parse();
285 if ( isset( $this->mValidationCallback
) ) {
286 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
292 function filter( $value, $alldata ) {
293 if ( isset( $this->mFilterCallback
) ) {
294 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
301 * Should this field have a label, or is there no input element with the
302 * appropriate id for the label to point to?
304 * @return bool True to output a label, false to suppress
306 protected function needsLabel() {
311 * Tell the field whether to generate a separate label element if its label
316 * @param bool $show Set to false to not generate a label.
319 public function setShowEmptyLabel( $show ) {
320 $this->mShowEmptyLabels
= $show;
324 * Get the value that this input has been set to from a posted form,
325 * or the input's default value if it has not been set.
327 * @param WebRequest $request
328 * @return string The value
330 function loadDataFromRequest( $request ) {
331 if ( $request->getCheck( $this->mName
) ) {
332 return $request->getText( $this->mName
);
334 return $this->getDefault();
339 * Initialise the object
341 * @param array $params Associative Array. See HTMLForm doc for syntax.
343 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
344 * @throws MWException
346 function __construct( $params ) {
347 $this->mParams
= $params;
349 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm
) {
350 $this->mParent
= $params['parent'];
353 # Generate the label from a message, if possible
354 if ( isset( $params['label-message'] ) ) {
355 $msgInfo = $params['label-message'];
357 if ( is_array( $msgInfo ) ) {
358 $msg = array_shift( $msgInfo );
364 $this->mLabel
= $this->msg( $msg, $msgInfo )->parse();
365 } elseif ( isset( $params['label'] ) ) {
366 if ( $params['label'] === ' ' ) {
367 // Apparently some things set   directly and in an odd format
368 $this->mLabel
= ' ';
370 $this->mLabel
= htmlspecialchars( $params['label'] );
372 } elseif ( isset( $params['label-raw'] ) ) {
373 $this->mLabel
= $params['label-raw'];
376 $this->mName
= "wp{$params['fieldname']}";
377 if ( isset( $params['name'] ) ) {
378 $this->mName
= $params['name'];
381 if ( isset( $params['dir'] ) ) {
382 $this->mDir
= $params['dir'];
385 $validName = Sanitizer
::escapeId( $this->mName
);
386 $validName = str_replace( array( '.5B', '.5D' ), array( '[', ']' ), $validName );
387 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
388 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
391 $this->mID
= "mw-input-{$this->mName}";
393 if ( isset( $params['default'] ) ) {
394 $this->mDefault
= $params['default'];
397 if ( isset( $params['id'] ) ) {
399 $validId = Sanitizer
::escapeId( $id );
401 if ( $id != $validId ) {
402 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
408 if ( isset( $params['cssclass'] ) ) {
409 $this->mClass
= $params['cssclass'];
412 if ( isset( $params['csshelpclass'] ) ) {
413 $this->mHelpClass
= $params['csshelpclass'];
416 if ( isset( $params['validation-callback'] ) ) {
417 $this->mValidationCallback
= $params['validation-callback'];
420 if ( isset( $params['filter-callback'] ) ) {
421 $this->mFilterCallback
= $params['filter-callback'];
424 if ( isset( $params['flatlist'] ) ) {
425 $this->mClass
.= ' mw-htmlform-flatlist';
428 if ( isset( $params['hidelabel'] ) ) {
429 $this->mShowEmptyLabels
= false;
432 if ( isset( $params['hide-if'] ) ) {
433 $this->mHideIf
= $params['hide-if'];
438 * Get the complete table row for the input, including help text,
439 * labels, and whatever.
441 * @param string $value The value to set the input to.
443 * @return string Complete HTML table row.
445 function getTableRow( $value ) {
446 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
447 $inputHtml = $this->getInputHTML( $value );
448 $fieldType = get_class( $this );
449 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
450 $cellAttributes = array();
451 $rowAttributes = array();
454 if ( !empty( $this->mParams
['vertical-label'] ) ) {
455 $cellAttributes['colspan'] = 2;
456 $verticalLabel = true;
458 $verticalLabel = false;
461 $label = $this->getLabelHtml( $cellAttributes );
463 $field = Html
::rawElement(
465 array( 'class' => 'mw-input' ) +
$cellAttributes,
466 $inputHtml . "\n$errors"
469 if ( $this->mHideIf
) {
470 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
471 $rowClasses .= ' mw-htmlform-hide-if';
474 if ( $verticalLabel ) {
475 $html = Html
::rawElement( 'tr',
476 $rowAttributes +
array( 'class' => "mw-htmlform-vertical-label $rowClasses" ), $label );
477 $html .= Html
::rawElement( 'tr',
478 $rowAttributes +
array(
479 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
484 Html
::rawElement( 'tr',
485 $rowAttributes +
array(
486 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
491 return $html . $helptext;
495 * Get the complete div for the input, including help text,
496 * labels, and whatever.
499 * @param string $value The value to set the input to.
501 * @return string Complete HTML table row.
503 public function getDiv( $value ) {
504 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
505 $inputHtml = $this->getInputHTML( $value );
506 $fieldType = get_class( $this );
507 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
508 $cellAttributes = array();
509 $label = $this->getLabelHtml( $cellAttributes );
511 $outerDivClass = array(
513 'mw-htmlform-nolabel' => ( $label === '' )
516 $field = Html
::rawElement(
518 array( 'class' => $outerDivClass ) +
$cellAttributes,
519 $inputHtml . "\n$errors"
521 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass
, $this->mVFormClass
, $errorClass );
523 $wrapperAttributes = array(
524 'class' => $divCssClasses,
526 if ( $this->mHideIf
) {
527 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
528 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
530 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
537 * Get the complete raw fields for the input, including help text,
538 * labels, and whatever.
541 * @param string $value The value to set the input to.
543 * @return string Complete HTML table row.
545 public function getRaw( $value ) {
546 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
547 $inputHtml = $this->getInputHTML( $value );
548 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
549 $cellAttributes = array();
550 $label = $this->getLabelHtml( $cellAttributes );
561 * Get the complete field for the input, including help text,
562 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
565 * @param string $value The value to set the input to.
566 * @return string Complete HTML field.
568 public function getVForm( $value ) {
570 $this->mVFormClass
= ' mw-ui-vform-field';
571 return $this->getDiv( $value );
575 * Get the complete field as an inline element.
577 * @param string $value The value to set the input to.
578 * @return string Complete HTML inline element
580 public function getInline( $value ) {
581 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
582 $inputHtml = $this->getInputHTML( $value );
583 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
584 $cellAttributes = array();
585 $label = $this->getLabelHtml( $cellAttributes );
587 $html = "\n" . $errors .
596 * Generate help text HTML in table format
599 * @param string|null $helptext
602 public function getHelpTextHtmlTable( $helptext ) {
603 if ( is_null( $helptext ) ) {
607 $rowAttributes = array();
608 if ( $this->mHideIf
) {
609 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
610 $rowAttributes['class'] = 'mw-htmlform-hide-if';
613 $tdClasses = array( 'htmlform-tip' );
614 if ( $this->mHelpClass
!== false ) {
615 $tdClasses[] = $this->mHelpClass
;
617 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => $tdClasses ), $helptext );
618 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
624 * Generate help text HTML in div format
627 * @param string|null $helptext
631 public function getHelpTextHtmlDiv( $helptext ) {
632 if ( is_null( $helptext ) ) {
636 $wrapperAttributes = array(
637 'class' => 'htmlform-tip',
639 if ( $this->mHelpClass
!== false ) {
640 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
642 if ( $this->mHideIf
) {
643 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
644 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
646 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
652 * Generate help text HTML formatted for raw output
655 * @param string|null $helptext
658 public function getHelpTextHtmlRaw( $helptext ) {
659 return $this->getHelpTextHtmlDiv( $helptext );
663 * Determine the help text to display
667 public function getHelpText() {
670 if ( isset( $this->mParams
['help-message'] ) ) {
671 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
674 if ( isset( $this->mParams
['help-messages'] ) ) {
675 foreach ( $this->mParams
['help-messages'] as $name ) {
676 $helpMessage = (array)$name;
677 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
679 if ( $msg->exists() ) {
680 if ( is_null( $helptext ) ) {
683 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
685 $helptext .= $msg->parse(); // Append message
688 } elseif ( isset( $this->mParams
['help'] ) ) {
689 $helptext = $this->mParams
['help'];
696 * Determine form errors to display and their classes
699 * @param string $value The value of the input
702 public function getErrorsAndErrorClass( $value ) {
703 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
705 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
709 $errors = self
::formatErrors( $errors );
710 $errorClass = 'mw-htmlform-invalid-input';
713 return array( $errors, $errorClass );
716 function getLabel() {
717 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
720 function getLabelHtml( $cellAttributes = array() ) {
721 # Don't output a for= attribute for labels with no associated input.
722 # Kind of hacky here, possibly we don't want these to be <label>s at all.
725 if ( $this->needsLabel() ) {
726 $for['for'] = $this->mID
;
729 $labelValue = trim( $this->getLabel() );
731 if ( $labelValue !== ' ' && $labelValue !== '' ) {
735 $displayFormat = $this->mParent
->getDisplayFormat();
738 if ( $displayFormat === 'table' ) {
740 Html
::rawElement( 'td',
741 array( 'class' => 'mw-label' ) +
$cellAttributes,
742 Html
::rawElement( 'label', $for, $labelValue ) );
743 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
744 if ( $displayFormat === 'div' ) {
746 Html
::rawElement( 'div',
747 array( 'class' => 'mw-label' ) +
$cellAttributes,
748 Html
::rawElement( 'label', $for, $labelValue ) );
750 $html = Html
::rawElement( 'label', $for, $labelValue );
757 function getDefault() {
758 if ( isset( $this->mDefault
) ) {
759 return $this->mDefault
;
766 * Returns the attributes required for the tooltip and accesskey.
768 * @return array Attributes
770 public function getTooltipAndAccessKey() {
771 if ( empty( $this->mParams
['tooltip'] ) ) {
775 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
779 * Returns the given attributes from the parameters
781 * @param array $list List of attributes to get
782 * @return array Attributes
784 public function getAttributes( array $list ) {
785 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
789 foreach ( $list as $key ) {
790 if ( in_array( $key, $boolAttribs ) ) {
791 if ( !empty( $this->mParams
[$key] ) ) {
794 } elseif ( isset( $this->mParams
[$key] ) ) {
795 $ret[$key] = $this->mParams
[$key];
803 * Given an array of msg-key => value mappings, returns an array with keys
804 * being the message texts. It also forces values to strings.
806 * @param array $options
809 private function lookupOptionsKeys( $options ) {
811 foreach ( $options as $key => $value ) {
812 $key = $this->msg( $key )->plain();
813 $ret[$key] = is_array( $value )
814 ?
$this->lookupOptionsKeys( $value )
821 * Recursively forces values in an array to strings, because issues arise
822 * with integer 0 as a value.
824 * @param array $array
827 static function forceToStringRecursive( $array ) {
828 if ( is_array( $array ) ) {
829 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
831 return strval( $array );
836 * Fetch the array of options from the field's parameters. In order, this
837 * checks 'options-messages', 'options', then 'options-message'.
839 * @return array|null Options array
841 public function getOptions() {
842 if ( $this->mOptions
=== false ) {
843 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
844 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
845 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
846 $this->mOptionsLabelsNotFromMessage
= true;
847 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
848 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
849 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
850 $message = $this->msg( $this->mParams
['options-message'] )->inContentLanguage()->plain();
853 $this->mOptions
= array();
854 foreach ( explode( "\n", $message ) as $option ) {
855 $value = trim( $option );
856 if ( $value == '' ) {
858 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
859 # A new group is starting...
860 $value = trim( substr( $value, 1 ) );
862 } elseif ( substr( $value, 0, 2 ) == '**' ) {
864 $opt = trim( substr( $value, 2 ) );
865 if ( $optgroup === false ) {
866 $this->mOptions
[$opt] = $opt;
868 $this->mOptions
[$optgroup][$opt] = $opt;
871 # groupless reason list
873 $this->mOptions
[$option] = $option;
877 $this->mOptions
= null;
881 return $this->mOptions
;
885 * flatten an array of options to a single array, for instance,
886 * a set of "<options>" inside "<optgroups>".
888 * @param array $options Associative Array with values either Strings or Arrays
889 * @return array Flattened input
891 public static function flattenOptions( $options ) {
894 foreach ( $options as $value ) {
895 if ( is_array( $value ) ) {
896 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
898 $flatOpts[] = $value;
906 * Formats one or more errors as accepted by field validation-callback.
908 * @param string|Message|array $errors Array of strings or Message instances
909 * @return string HTML
912 protected static function formatErrors( $errors ) {
913 if ( is_array( $errors ) && count( $errors ) === 1 ) {
914 $errors = array_shift( $errors );
917 if ( is_array( $errors ) ) {
919 foreach ( $errors as $error ) {
920 if ( $error instanceof Message
) {
921 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
923 $lines[] = Html
::rawElement( 'li', array(), $error );
927 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
929 if ( $errors instanceof Message
) {
930 $errors = $errors->parse();
933 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );