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;
13 protected $mLabel; # String label. Set on construction
15 protected $mClass = '';
17 protected $mOptions = false;
18 protected $mOptionsLabelsNotFromMessage = false;
19 protected $mHideIf = null;
22 * @var bool If true will generate an empty div element with no label
25 protected $mShowEmptyLabels = true;
33 * This function must be implemented to return the HTML to generate
34 * the input object itself. It should not implement the surrounding
35 * table cells/rows, or labels/help messages.
37 * @param string $value the value to set the input to; eg a default
38 * text for a text input.
40 * @return string Valid HTML.
42 abstract function getInputHTML( $value );
45 * Get a translated interface message
47 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
48 * and wfMessage() otherwise.
50 * Parameters are the same as wfMessage().
55 $args = func_get_args();
57 if ( $this->mParent
) {
58 $callback = array( $this->mParent
, 'msg' );
60 $callback = 'wfMessage';
63 return call_user_func_array( $callback, $args );
68 * Fetch a field value from $alldata for the closest field matching a given
71 * This is complex because it needs to handle array fields like the user
72 * would expect. The general algorithm is to look for $name as a sibling
73 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
74 * that $name itself might be referencing an array.
76 * @param array $alldata
80 protected function getNearestFieldByName( $alldata, $name ) {
83 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
84 array_unshift( $thisKeys, $m[2] );
87 if ( substr( $tmp, 0, 2 ) == 'wp' &&
88 !isset( $alldata[$tmp] ) &&
89 isset( $alldata[substr( $tmp, 2 )] )
91 // Adjust for name mangling.
92 $tmp = substr( $tmp, 2 );
94 array_unshift( $thisKeys, $tmp );
98 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
99 array_unshift( $nameKeys, $m[2] );
102 array_unshift( $nameKeys, $tmp );
105 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
106 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
109 $key = array_shift( $keys );
110 if ( !is_array( $data ) ||
!isset( $data[$key] ) ) {
123 * Helper function for isHidden to handle recursive data structures.
125 * @param array $alldata
126 * @param array $params
129 protected function isHiddenRecurse( array $alldata, array $params ) {
130 $origParams = $params;
131 $op = array_shift( $params );
136 foreach ( $params as $i => $p ) {
137 if ( !is_array( $p ) ) {
138 throw new MWException(
139 "Expected array, found " . gettype( $p ) . " at index $i"
142 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
149 foreach ( $params as $p ) {
150 if ( !is_array( $p ) ) {
151 throw new MWException(
152 "Expected array, found " . gettype( $p ) . " at index $i"
155 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
162 foreach ( $params as $i => $p ) {
163 if ( !is_array( $p ) ) {
164 throw new MWException(
165 "Expected array, found " . gettype( $p ) . " at index $i"
168 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
175 foreach ( $params as $p ) {
176 if ( !is_array( $p ) ) {
177 throw new MWException(
178 "Expected array, found " . gettype( $p ) . " at index $i"
181 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
188 if ( count( $params ) !== 1 ) {
189 throw new MWException( "NOT takes exactly one parameter" );
192 if ( !is_array( $p ) ) {
193 throw new MWException(
194 "Expected array, found " . gettype( $p ) . " at index 0"
197 return !$this->isHiddenRecurse( $alldata, $p );
201 if ( count( $params ) !== 2 ) {
202 throw new MWException( "$op takes exactly two parameters" );
204 list( $field, $value ) = $params;
205 if ( !is_string( $field ) ||
!is_string( $value ) ) {
206 throw new MWException( "Parameters for $op must be strings" );
208 $testValue = $this->getNearestFieldByName( $alldata, $field );
211 return ( $value === $testValue );
213 return ( $value !== $testValue );
217 throw new MWException( "Unknown operation" );
219 } catch ( MWException
$ex ) {
220 throw new MWException(
221 "Invalid hide-if specification for $this->mName: " .
222 $ex->getMessage() . " in " . var_export( $origParams, true ),
229 * Test whether this field is supposed to be hidden, based on the values of
230 * the other form fields.
233 * @param array $alldata The data collected from the form
236 function isHidden( $alldata ) {
237 if ( !$this->mHideIf
) {
241 return $this->isHiddenRecurse( $alldata, $this->mHideIf
);
245 * Override this function to add specific validation checks on the
246 * field input. Don't forget to call parent::validate() to ensure
247 * that the user-defined callback mValidationCallback is still run
249 * @param string $value The value the field was submitted with
250 * @param array $alldata The data collected from the form
252 * @return bool|string true on success, or String error to display.
254 function validate( $value, $alldata ) {
255 if ( $this->isHidden( $alldata ) ) {
259 if ( isset( $this->mParams
['required'] )
260 && $this->mParams
['required'] !== false
263 return $this->msg( 'htmlform-required' )->parse();
266 if ( isset( $this->mValidationCallback
) ) {
267 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
273 function filter( $value, $alldata ) {
274 if ( isset( $this->mFilterCallback
) ) {
275 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
282 * Should this field have a label, or is there no input element with the
283 * appropriate id for the label to point to?
285 * @return bool True to output a label, false to suppress
287 protected function needsLabel() {
292 * Tell the field whether to generate a separate label element if its label
297 * @param bool $show Set to false to not generate a label.
300 public function setShowEmptyLabel( $show ) {
301 $this->mShowEmptyLabels
= $show;
305 * Get the value that this input has been set to from a posted form,
306 * or the input's default value if it has not been set.
308 * @param WebRequest $request
309 * @return string The value
311 function loadDataFromRequest( $request ) {
312 if ( $request->getCheck( $this->mName
) ) {
313 return $request->getText( $this->mName
);
315 return $this->getDefault();
320 * Initialise the object
322 * @param array $params Associative Array. See HTMLForm doc for syntax.
324 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
325 * @throws MWException
327 function __construct( $params ) {
328 $this->mParams
= $params;
330 # Generate the label from a message, if possible
331 if ( isset( $params['label-message'] ) ) {
332 $msgInfo = $params['label-message'];
334 if ( is_array( $msgInfo ) ) {
335 $msg = array_shift( $msgInfo );
341 $this->mLabel
= wfMessage( $msg, $msgInfo )->parse();
342 } elseif ( isset( $params['label'] ) ) {
343 if ( $params['label'] === ' ' ) {
344 // Apparently some things set   directly and in an odd format
345 $this->mLabel
= ' ';
347 $this->mLabel
= htmlspecialchars( $params['label'] );
349 } elseif ( isset( $params['label-raw'] ) ) {
350 $this->mLabel
= $params['label-raw'];
353 $this->mName
= "wp{$params['fieldname']}";
354 if ( isset( $params['name'] ) ) {
355 $this->mName
= $params['name'];
358 $validName = Sanitizer
::escapeId( $this->mName
);
359 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
360 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
363 $this->mID
= "mw-input-{$this->mName}";
365 if ( isset( $params['default'] ) ) {
366 $this->mDefault
= $params['default'];
369 if ( isset( $params['id'] ) ) {
371 $validId = Sanitizer
::escapeId( $id );
373 if ( $id != $validId ) {
374 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
380 if ( isset( $params['cssclass'] ) ) {
381 $this->mClass
= $params['cssclass'];
384 if ( isset( $params['validation-callback'] ) ) {
385 $this->mValidationCallback
= $params['validation-callback'];
388 if ( isset( $params['filter-callback'] ) ) {
389 $this->mFilterCallback
= $params['filter-callback'];
392 if ( isset( $params['flatlist'] ) ) {
393 $this->mClass
.= ' mw-htmlform-flatlist';
396 if ( isset( $params['hidelabel'] ) ) {
397 $this->mShowEmptyLabels
= false;
400 if ( isset( $params['hide-if'] ) ) {
401 $this->mHideIf
= $params['hide-if'];
406 * Get the complete table row for the input, including help text,
407 * labels, and whatever.
409 * @param string $value The value to set the input to.
411 * @return string Complete HTML table row.
413 function getTableRow( $value ) {
414 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
415 $inputHtml = $this->getInputHTML( $value );
416 $fieldType = get_class( $this );
417 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
418 $cellAttributes = array();
419 $rowAttributes = array();
422 if ( !empty( $this->mParams
['vertical-label'] ) ) {
423 $cellAttributes['colspan'] = 2;
424 $verticalLabel = true;
426 $verticalLabel = false;
429 $label = $this->getLabelHtml( $cellAttributes );
431 $field = Html
::rawElement(
433 array( 'class' => 'mw-input' ) +
$cellAttributes,
434 $inputHtml . "\n$errors"
437 if ( $this->mHideIf
) {
438 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
439 $rowClasses .= ' mw-htmlform-hide-if';
442 if ( $verticalLabel ) {
443 $html = Html
::rawElement( 'tr',
444 $rowAttributes +
array( 'class' => "mw-htmlform-vertical-label $rowClasses" ), $label );
445 $html .= Html
::rawElement( 'tr',
446 $rowAttributes +
array(
447 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
452 Html
::rawElement( 'tr',
453 $rowAttributes +
array(
454 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
459 return $html . $helptext;
463 * Get the complete div for the input, including help text,
464 * labels, and whatever.
467 * @param string $value The value to set the input to.
469 * @return string Complete HTML table row.
471 public function getDiv( $value ) {
472 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
473 $inputHtml = $this->getInputHTML( $value );
474 $fieldType = get_class( $this );
475 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
476 $cellAttributes = array();
477 $label = $this->getLabelHtml( $cellAttributes );
479 $outerDivClass = array(
481 'mw-htmlform-nolabel' => ( $label === '' )
484 $field = Html
::rawElement(
486 array( 'class' => $outerDivClass ) +
$cellAttributes,
487 $inputHtml . "\n$errors"
489 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass
, $errorClass );
490 if ( $this->mParent
->isVForm() ) {
491 $divCssClasses[] = 'mw-ui-vform-div';
494 $wrapperAttributes = array(
495 'class' => $divCssClasses,
497 if ( $this->mHideIf
) {
498 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
499 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
501 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
508 * Get the complete raw fields for the input, including help text,
509 * labels, and whatever.
512 * @param string $value The value to set the input to.
514 * @return string Complete HTML table row.
516 public function getRaw( $value ) {
517 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
518 $inputHtml = $this->getInputHTML( $value );
519 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
520 $cellAttributes = array();
521 $label = $this->getLabelHtml( $cellAttributes );
532 * Generate help text HTML in table format
535 * @param string|null $helptext
538 public function getHelpTextHtmlTable( $helptext ) {
539 if ( is_null( $helptext ) ) {
543 $rowAttributes = array();
544 if ( $this->mHideIf
) {
545 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
546 $rowAttributes['class'] = 'mw-htmlform-hide-if';
549 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ), $helptext );
550 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
556 * Generate help text HTML in div format
559 * @param string|null $helptext
563 public function getHelpTextHtmlDiv( $helptext ) {
564 if ( is_null( $helptext ) ) {
568 $wrapperAttributes = array(
569 'class' => 'htmlform-tip',
571 if ( $this->mHideIf
) {
572 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
573 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
575 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
581 * Generate help text HTML formatted for raw output
584 * @param string|null $helptext
587 public function getHelpTextHtmlRaw( $helptext ) {
588 return $this->getHelpTextHtmlDiv( $helptext );
592 * Determine the help text to display
596 public function getHelpText() {
599 if ( isset( $this->mParams
['help-message'] ) ) {
600 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
603 if ( isset( $this->mParams
['help-messages'] ) ) {
604 foreach ( $this->mParams
['help-messages'] as $name ) {
605 $helpMessage = (array)$name;
606 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
608 if ( $msg->exists() ) {
609 if ( is_null( $helptext ) ) {
612 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
614 $helptext .= $msg->parse(); // Append message
617 } elseif ( isset( $this->mParams
['help'] ) ) {
618 $helptext = $this->mParams
['help'];
625 * Determine form errors to display and their classes
628 * @param string $value The value of the input
631 public function getErrorsAndErrorClass( $value ) {
632 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
634 if ( $errors === true ||
635 ( !$this->mParent
->getRequest()->wasPosted() && $this->mParent
->getMethod() === 'post' )
640 $errors = self
::formatErrors( $errors );
641 $errorClass = 'mw-htmlform-invalid-input';
644 return array( $errors, $errorClass );
647 function getLabel() {
648 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
651 function getLabelHtml( $cellAttributes = array() ) {
652 # Don't output a for= attribute for labels with no associated input.
653 # Kind of hacky here, possibly we don't want these to be <label>s at all.
656 if ( $this->needsLabel() ) {
657 $for['for'] = $this->mID
;
660 $labelValue = trim( $this->getLabel() );
662 if ( $labelValue !== ' ' && $labelValue !== '' ) {
666 $displayFormat = $this->mParent
->getDisplayFormat();
669 if ( $displayFormat === 'table' ) {
671 Html
::rawElement( 'td',
672 array( 'class' => 'mw-label' ) +
$cellAttributes,
673 Html
::rawElement( 'label', $for, $labelValue ) );
674 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
675 if ( $displayFormat === 'div' ) {
677 Html
::rawElement( 'div',
678 array( 'class' => 'mw-label' ) +
$cellAttributes,
679 Html
::rawElement( 'label', $for, $labelValue ) );
681 $html = Html
::rawElement( 'label', $for, $labelValue );
688 function getDefault() {
689 if ( isset( $this->mDefault
) ) {
690 return $this->mDefault
;
697 * Returns the attributes required for the tooltip and accesskey.
699 * @return array Attributes
701 public function getTooltipAndAccessKey() {
702 if ( empty( $this->mParams
['tooltip'] ) ) {
706 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
710 * Returns the given attributes from the parameters
712 * @param array $list List of attributes to get
713 * @return array Attributes
715 public function getAttributes( array $list ) {
716 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
720 foreach ( $list as $key ) {
721 if ( in_array( $key, $boolAttribs ) ) {
722 if ( !empty( $this->mParams
[$key] ) ) {
725 } elseif ( isset( $this->mParams
[$key] ) ) {
726 $ret[$key] = $this->mParams
[$key];
734 * Given an array of msg-key => value mappings, returns an array with keys
735 * being the message texts. It also forces values to strings.
737 * @param array $options
740 private function lookupOptionsKeys( $options ) {
742 foreach ( $options as $key => $value ) {
743 $key = $this->msg( $key )->plain();
744 $ret[$key] = is_array( $value )
745 ?
$this->lookupOptionsKeys( $value )
752 * Recursively forces values in an array to strings, because issues arise
753 * with integer 0 as a value.
755 * @param array $array
758 static function forceToStringRecursive( $array ) {
759 if ( is_array( $array ) ) {
760 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
762 return strval( $array );
767 * Fetch the array of options from the field's parameters. In order, this
768 * checks 'options-messages', 'options', then 'options-message'.
770 * @return array|null Options array
772 public function getOptions() {
773 if ( $this->mOptions
=== false ) {
774 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
775 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
776 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
777 $this->mOptionsLabelsNotFromMessage
= true;
778 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
779 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
780 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
781 $message = $this->msg( $this->mParams
['options-message'] )->inContentLanguage()->plain();
784 $this->mOptions
= array();
785 foreach ( explode( "\n", $message ) as $option ) {
786 $value = trim( $option );
787 if ( $value == '' ) {
789 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
790 # A new group is starting...
791 $value = trim( substr( $value, 1 ) );
793 } elseif ( substr( $value, 0, 2 ) == '**' ) {
795 $opt = trim( substr( $value, 2 ) );
796 if ( $optgroup === false ) {
797 $this->mOptions
[$opt] = $opt;
799 $this->mOptions
[$optgroup][$opt] = $opt;
802 # groupless reason list
804 $this->mOptions
[$option] = $option;
808 $this->mOptions
= null;
812 return $this->mOptions
;
816 * flatten an array of options to a single array, for instance,
817 * a set of "<options>" inside "<optgroups>".
819 * @param array $options Associative Array with values either Strings or Arrays
820 * @return array Flattened input
822 public static function flattenOptions( $options ) {
825 foreach ( $options as $value ) {
826 if ( is_array( $value ) ) {
827 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
829 $flatOpts[] = $value;
837 * Formats one or more errors as accepted by field validation-callback.
839 * @param string|Message|array $errors Array of strings or Message instances
840 * @return string HTML
843 protected static function formatErrors( $errors ) {
844 if ( is_array( $errors ) && count( $errors ) === 1 ) {
845 $errors = array_shift( $errors );
848 if ( is_array( $errors ) ) {
850 foreach ( $errors as $error ) {
851 if ( $error instanceof Message
) {
852 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
854 $lines[] = Html
::rawElement( 'li', array(), $error );
858 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
860 if ( $errors instanceof Message
) {
861 $errors = $errors->parse();
864 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );