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 = '';
16 protected $mHelpClass = false;
18 protected $mOptions = false;
19 protected $mOptionsLabelsNotFromMessage = false;
20 protected $mHideIf = null;
23 * @var bool If true will generate an empty div element with no label
26 protected $mShowEmptyLabels = true;
34 * This function must be implemented to return the HTML to generate
35 * the input object itself. It should not implement the surrounding
36 * table cells/rows, or labels/help messages.
38 * @param string $value The value to set the input to; eg a default
39 * text for a text input.
41 * @return string Valid HTML.
43 abstract function getInputHTML( $value );
46 * Get a translated interface message
48 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
49 * and wfMessage() otherwise.
51 * Parameters are the same as wfMessage().
56 $args = func_get_args();
58 if ( $this->mParent
) {
59 $callback = array( $this->mParent
, 'msg' );
61 $callback = 'wfMessage';
64 return call_user_func_array( $callback, $args );
69 * Fetch a field value from $alldata for the closest field matching a given
72 * This is complex because it needs to handle array fields like the user
73 * would expect. The general algorithm is to look for $name as a sibling
74 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
75 * that $name itself might be referencing an array.
77 * @param array $alldata
81 protected function getNearestFieldByName( $alldata, $name ) {
84 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
85 array_unshift( $thisKeys, $m[2] );
88 if ( substr( $tmp, 0, 2 ) == 'wp' &&
89 !isset( $alldata[$tmp] ) &&
90 isset( $alldata[substr( $tmp, 2 )] )
92 // Adjust for name mangling.
93 $tmp = substr( $tmp, 2 );
95 array_unshift( $thisKeys, $tmp );
99 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
100 array_unshift( $nameKeys, $m[2] );
103 array_unshift( $nameKeys, $tmp );
106 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
107 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
110 $key = array_shift( $keys );
111 if ( !is_array( $data ) ||
!isset( $data[$key] ) ) {
116 $testValue = (string)$data;
124 * Helper function for isHidden to handle recursive data structures.
126 * @param array $alldata
127 * @param array $params
129 * @throws MWException
131 protected function isHiddenRecurse( array $alldata, array $params ) {
132 $origParams = $params;
133 $op = array_shift( $params );
138 foreach ( $params as $i => $p ) {
139 if ( !is_array( $p ) ) {
140 throw new MWException(
141 "Expected array, found " . gettype( $p ) . " at index $i"
144 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
151 foreach ( $params as $p ) {
152 if ( !is_array( $p ) ) {
153 throw new MWException(
154 "Expected array, found " . gettype( $p ) . " at index $i"
157 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
164 foreach ( $params as $i => $p ) {
165 if ( !is_array( $p ) ) {
166 throw new MWException(
167 "Expected array, found " . gettype( $p ) . " at index $i"
170 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
177 foreach ( $params as $p ) {
178 if ( !is_array( $p ) ) {
179 throw new MWException(
180 "Expected array, found " . gettype( $p ) . " at index $i"
183 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
190 if ( count( $params ) !== 1 ) {
191 throw new MWException( "NOT takes exactly one parameter" );
194 if ( !is_array( $p ) ) {
195 throw new MWException(
196 "Expected array, found " . gettype( $p ) . " at index 0"
199 return !$this->isHiddenRecurse( $alldata, $p );
203 if ( count( $params ) !== 2 ) {
204 throw new MWException( "$op takes exactly two parameters" );
206 list( $field, $value ) = $params;
207 if ( !is_string( $field ) ||
!is_string( $value ) ) {
208 throw new MWException( "Parameters for $op must be strings" );
210 $testValue = $this->getNearestFieldByName( $alldata, $field );
213 return ( $value === $testValue );
215 return ( $value !== $testValue );
219 throw new MWException( "Unknown operation" );
221 } catch ( Exception
$ex ) {
222 throw new MWException(
223 "Invalid hide-if specification for $this->mName: " .
224 $ex->getMessage() . " in " . var_export( $origParams, true ),
231 * Test whether this field is supposed to be hidden, based on the values of
232 * the other form fields.
235 * @param array $alldata The data collected from the form
238 function isHidden( $alldata ) {
239 if ( !$this->mHideIf
) {
243 return $this->isHiddenRecurse( $alldata, $this->mHideIf
);
247 * Override this function if the control can somehow trigger a form
248 * submission that shouldn't actually submit the HTMLForm.
251 * @param string|array $value The value the field was submitted with
252 * @param array $alldata The data collected from the form
254 * @return bool True to cancel the submission
256 function cancelSubmit( $value, $alldata ) {
261 * Override this function to add specific validation checks on the
262 * field input. Don't forget to call parent::validate() to ensure
263 * that the user-defined callback mValidationCallback is still run
265 * @param string|array $value The value the field was submitted with
266 * @param array $alldata The data collected from the form
268 * @return bool|string True on success, or String error to display, or
269 * false to fail validation without displaying an error.
271 function validate( $value, $alldata ) {
272 if ( $this->isHidden( $alldata ) ) {
276 if ( isset( $this->mParams
['required'] )
277 && $this->mParams
['required'] !== false
280 return $this->msg( 'htmlform-required' )->parse();
283 if ( isset( $this->mValidationCallback
) ) {
284 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
290 function filter( $value, $alldata ) {
291 if ( isset( $this->mFilterCallback
) ) {
292 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
299 * Should this field have a label, or is there no input element with the
300 * appropriate id for the label to point to?
302 * @return bool True to output a label, false to suppress
304 protected function needsLabel() {
309 * Tell the field whether to generate a separate label element if its label
314 * @param bool $show Set to false to not generate a label.
317 public function setShowEmptyLabel( $show ) {
318 $this->mShowEmptyLabels
= $show;
322 * Get the value that this input has been set to from a posted form,
323 * or the input's default value if it has not been set.
325 * @param WebRequest $request
326 * @return string The value
328 function loadDataFromRequest( $request ) {
329 if ( $request->getCheck( $this->mName
) ) {
330 return $request->getText( $this->mName
);
332 return $this->getDefault();
337 * Initialise the object
339 * @param array $params Associative Array. See HTMLForm doc for syntax.
341 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
342 * @throws MWException
344 function __construct( $params ) {
345 $this->mParams
= $params;
347 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm
) {
348 $this->mParent
= $params['parent'];
351 # Generate the label from a message, if possible
352 if ( isset( $params['label-message'] ) ) {
353 $msgInfo = $params['label-message'];
355 if ( is_array( $msgInfo ) ) {
356 $msg = array_shift( $msgInfo );
362 $this->mLabel
= $this->msg( $msg, $msgInfo )->parse();
363 } elseif ( isset( $params['label'] ) ) {
364 if ( $params['label'] === ' ' ) {
365 // Apparently some things set   directly and in an odd format
366 $this->mLabel
= ' ';
368 $this->mLabel
= htmlspecialchars( $params['label'] );
370 } elseif ( isset( $params['label-raw'] ) ) {
371 $this->mLabel
= $params['label-raw'];
374 $this->mName
= "wp{$params['fieldname']}";
375 if ( isset( $params['name'] ) ) {
376 $this->mName
= $params['name'];
379 $validName = Sanitizer
::escapeId( $this->mName
);
380 $validName = str_replace( array( '.5B', '.5D' ), array( '[', ']' ), $validName );
381 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
382 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
385 $this->mID
= "mw-input-{$this->mName}";
387 if ( isset( $params['default'] ) ) {
388 $this->mDefault
= $params['default'];
391 if ( isset( $params['id'] ) ) {
393 $validId = Sanitizer
::escapeId( $id );
395 if ( $id != $validId ) {
396 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
402 if ( isset( $params['cssclass'] ) ) {
403 $this->mClass
= $params['cssclass'];
406 if ( isset( $params['csshelpclass'] ) ) {
407 $this->mHelpClass
= $params['csshelpclass'];
410 if ( isset( $params['validation-callback'] ) ) {
411 $this->mValidationCallback
= $params['validation-callback'];
414 if ( isset( $params['filter-callback'] ) ) {
415 $this->mFilterCallback
= $params['filter-callback'];
418 if ( isset( $params['flatlist'] ) ) {
419 $this->mClass
.= ' mw-htmlform-flatlist';
422 if ( isset( $params['hidelabel'] ) ) {
423 $this->mShowEmptyLabels
= false;
426 if ( isset( $params['hide-if'] ) ) {
427 $this->mHideIf
= $params['hide-if'];
432 * Get the complete table row for the input, including help text,
433 * labels, and whatever.
435 * @param string $value The value to set the input to.
437 * @return string Complete HTML table row.
439 function getTableRow( $value ) {
440 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
441 $inputHtml = $this->getInputHTML( $value );
442 $fieldType = get_class( $this );
443 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
444 $cellAttributes = array();
445 $rowAttributes = array();
448 if ( !empty( $this->mParams
['vertical-label'] ) ) {
449 $cellAttributes['colspan'] = 2;
450 $verticalLabel = true;
452 $verticalLabel = false;
455 $label = $this->getLabelHtml( $cellAttributes );
457 $field = Html
::rawElement(
459 array( 'class' => 'mw-input' ) +
$cellAttributes,
460 $inputHtml . "\n$errors"
463 if ( $this->mHideIf
) {
464 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
465 $rowClasses .= ' mw-htmlform-hide-if';
468 if ( $verticalLabel ) {
469 $html = Html
::rawElement( 'tr',
470 $rowAttributes +
array( 'class' => "mw-htmlform-vertical-label $rowClasses" ), $label );
471 $html .= Html
::rawElement( 'tr',
472 $rowAttributes +
array(
473 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
478 Html
::rawElement( 'tr',
479 $rowAttributes +
array(
480 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
485 return $html . $helptext;
489 * Get the complete div for the input, including help text,
490 * labels, and whatever.
493 * @param string $value The value to set the input to.
495 * @return string Complete HTML table row.
497 public function getDiv( $value ) {
498 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
499 $inputHtml = $this->getInputHTML( $value );
500 $fieldType = get_class( $this );
501 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
502 $cellAttributes = array();
503 $label = $this->getLabelHtml( $cellAttributes );
505 $outerDivClass = array(
507 'mw-htmlform-nolabel' => ( $label === '' )
510 $field = Html
::rawElement(
512 array( 'class' => $outerDivClass ) +
$cellAttributes,
513 $inputHtml . "\n$errors"
515 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass
, $errorClass );
517 $wrapperAttributes = array(
518 'class' => $divCssClasses,
520 if ( $this->mHideIf
) {
521 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
522 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
524 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
531 * Get the complete raw fields for the input, including help text,
532 * labels, and whatever.
535 * @param string $value The value to set the input to.
537 * @return string Complete HTML table row.
539 public function getRaw( $value ) {
540 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
541 $inputHtml = $this->getInputHTML( $value );
542 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
543 $cellAttributes = array();
544 $label = $this->getLabelHtml( $cellAttributes );
555 * Get the complete field for the input, including help text,
556 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
559 * @param string $value The value to set the input to.
560 * @return string Complete HTML field.
562 public function getVForm( $value ) {
564 $this->mClass
.= ' mw-ui-vform-field';
565 return $this->getDiv( $value );
569 * Generate help text HTML in table format
572 * @param string|null $helptext
575 public function getHelpTextHtmlTable( $helptext ) {
576 if ( is_null( $helptext ) ) {
580 $rowAttributes = array();
581 if ( $this->mHideIf
) {
582 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
583 $rowAttributes['class'] = 'mw-htmlform-hide-if';
586 $tdClasses = array( 'htmlform-tip' );
587 if ( $this->mHelpClass
!== false ) {
588 $tdClasses[] = $this->mHelpClass
;
590 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => $tdClasses ), $helptext );
591 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
597 * Generate help text HTML in div format
600 * @param string|null $helptext
604 public function getHelpTextHtmlDiv( $helptext ) {
605 if ( is_null( $helptext ) ) {
609 $wrapperAttributes = array(
610 'class' => 'htmlform-tip',
612 if ( $this->mHelpClass
!== false ) {
613 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
615 if ( $this->mHideIf
) {
616 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
617 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
619 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
625 * Generate help text HTML formatted for raw output
628 * @param string|null $helptext
631 public function getHelpTextHtmlRaw( $helptext ) {
632 return $this->getHelpTextHtmlDiv( $helptext );
636 * Determine the help text to display
640 public function getHelpText() {
643 if ( isset( $this->mParams
['help-message'] ) ) {
644 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
647 if ( isset( $this->mParams
['help-messages'] ) ) {
648 foreach ( $this->mParams
['help-messages'] as $name ) {
649 $helpMessage = (array)$name;
650 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
652 if ( $msg->exists() ) {
653 if ( is_null( $helptext ) ) {
656 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
658 $helptext .= $msg->parse(); // Append message
661 } elseif ( isset( $this->mParams
['help'] ) ) {
662 $helptext = $this->mParams
['help'];
669 * Determine form errors to display and their classes
672 * @param string $value The value of the input
675 public function getErrorsAndErrorClass( $value ) {
676 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
678 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
682 $errors = self
::formatErrors( $errors );
683 $errorClass = 'mw-htmlform-invalid-input';
686 return array( $errors, $errorClass );
689 function getLabel() {
690 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
693 function getLabelHtml( $cellAttributes = array() ) {
694 # Don't output a for= attribute for labels with no associated input.
695 # Kind of hacky here, possibly we don't want these to be <label>s at all.
698 if ( $this->needsLabel() ) {
699 $for['for'] = $this->mID
;
702 $labelValue = trim( $this->getLabel() );
704 if ( $labelValue !== ' ' && $labelValue !== '' ) {
708 $displayFormat = $this->mParent
->getDisplayFormat();
711 if ( $displayFormat === 'table' ) {
713 Html
::rawElement( 'td',
714 array( 'class' => 'mw-label' ) +
$cellAttributes,
715 Html
::rawElement( 'label', $for, $labelValue ) );
716 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
717 if ( $displayFormat === 'div' ) {
719 Html
::rawElement( 'div',
720 array( 'class' => 'mw-label' ) +
$cellAttributes,
721 Html
::rawElement( 'label', $for, $labelValue ) );
723 $html = Html
::rawElement( 'label', $for, $labelValue );
730 function getDefault() {
731 if ( isset( $this->mDefault
) ) {
732 return $this->mDefault
;
739 * Returns the attributes required for the tooltip and accesskey.
741 * @return array Attributes
743 public function getTooltipAndAccessKey() {
744 if ( empty( $this->mParams
['tooltip'] ) ) {
748 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
752 * Returns the given attributes from the parameters
754 * @param array $list List of attributes to get
755 * @return array Attributes
757 public function getAttributes( array $list ) {
758 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
762 foreach ( $list as $key ) {
763 if ( in_array( $key, $boolAttribs ) ) {
764 if ( !empty( $this->mParams
[$key] ) ) {
767 } elseif ( isset( $this->mParams
[$key] ) ) {
768 $ret[$key] = $this->mParams
[$key];
776 * Given an array of msg-key => value mappings, returns an array with keys
777 * being the message texts. It also forces values to strings.
779 * @param array $options
782 private function lookupOptionsKeys( $options ) {
784 foreach ( $options as $key => $value ) {
785 $key = $this->msg( $key )->plain();
786 $ret[$key] = is_array( $value )
787 ?
$this->lookupOptionsKeys( $value )
794 * Recursively forces values in an array to strings, because issues arise
795 * with integer 0 as a value.
797 * @param array $array
800 static function forceToStringRecursive( $array ) {
801 if ( is_array( $array ) ) {
802 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
804 return strval( $array );
809 * Fetch the array of options from the field's parameters. In order, this
810 * checks 'options-messages', 'options', then 'options-message'.
812 * @return array|null Options array
814 public function getOptions() {
815 if ( $this->mOptions
=== false ) {
816 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
817 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
818 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
819 $this->mOptionsLabelsNotFromMessage
= true;
820 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
821 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
822 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
823 $message = $this->msg( $this->mParams
['options-message'] )->inContentLanguage()->plain();
826 $this->mOptions
= array();
827 foreach ( explode( "\n", $message ) as $option ) {
828 $value = trim( $option );
829 if ( $value == '' ) {
831 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
832 # A new group is starting...
833 $value = trim( substr( $value, 1 ) );
835 } elseif ( substr( $value, 0, 2 ) == '**' ) {
837 $opt = trim( substr( $value, 2 ) );
838 if ( $optgroup === false ) {
839 $this->mOptions
[$opt] = $opt;
841 $this->mOptions
[$optgroup][$opt] = $opt;
844 # groupless reason list
846 $this->mOptions
[$option] = $option;
850 $this->mOptions
= null;
854 return $this->mOptions
;
858 * flatten an array of options to a single array, for instance,
859 * a set of "<options>" inside "<optgroups>".
861 * @param array $options Associative Array with values either Strings or Arrays
862 * @return array Flattened input
864 public static function flattenOptions( $options ) {
867 foreach ( $options as $value ) {
868 if ( is_array( $value ) ) {
869 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
871 $flatOpts[] = $value;
879 * Formats one or more errors as accepted by field validation-callback.
881 * @param string|Message|array $errors Array of strings or Message instances
882 * @return string HTML
885 protected static function formatErrors( $errors ) {
886 if ( is_array( $errors ) && count( $errors ) === 1 ) {
887 $errors = array_shift( $errors );
890 if ( is_array( $errors ) ) {
892 foreach ( $errors as $error ) {
893 if ( $error instanceof Message
) {
894 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
896 $lines[] = Html
::rawElement( 'li', array(), $error );
900 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
902 if ( $errors instanceof Message
) {
903 $errors = $errors->parse();
906 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );