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
130 protected function isHiddenRecurse( array $alldata, array $params ) {
131 $origParams = $params;
132 $op = array_shift( $params );
137 foreach ( $params as $i => $p ) {
138 if ( !is_array( $p ) ) {
139 throw new MWException(
140 "Expected array, found " . gettype( $p ) . " at index $i"
143 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
150 foreach ( $params as $p ) {
151 if ( !is_array( $p ) ) {
152 throw new MWException(
153 "Expected array, found " . gettype( $p ) . " at index $i"
156 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
163 foreach ( $params as $i => $p ) {
164 if ( !is_array( $p ) ) {
165 throw new MWException(
166 "Expected array, found " . gettype( $p ) . " at index $i"
169 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
176 foreach ( $params as $p ) {
177 if ( !is_array( $p ) ) {
178 throw new MWException(
179 "Expected array, found " . gettype( $p ) . " at index $i"
182 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
189 if ( count( $params ) !== 1 ) {
190 throw new MWException( "NOT takes exactly one parameter" );
193 if ( !is_array( $p ) ) {
194 throw new MWException(
195 "Expected array, found " . gettype( $p ) . " at index 0"
198 return !$this->isHiddenRecurse( $alldata, $p );
202 if ( count( $params ) !== 2 ) {
203 throw new MWException( "$op takes exactly two parameters" );
205 list( $field, $value ) = $params;
206 if ( !is_string( $field ) ||
!is_string( $value ) ) {
207 throw new MWException( "Parameters for $op must be strings" );
209 $testValue = $this->getNearestFieldByName( $alldata, $field );
212 return ( $value === $testValue );
214 return ( $value !== $testValue );
218 throw new MWException( "Unknown operation" );
220 } catch ( MWException
$ex ) {
221 throw new MWException(
222 "Invalid hide-if specification for $this->mName: " .
223 $ex->getMessage() . " in " . var_export( $origParams, true ),
230 * Test whether this field is supposed to be hidden, based on the values of
231 * the other form fields.
234 * @param array $alldata The data collected from the form
237 function isHidden( $alldata ) {
238 if ( !$this->mHideIf
) {
242 return $this->isHiddenRecurse( $alldata, $this->mHideIf
);
246 * Override this function if the control can somehow trigger a form
247 * submission that shouldn't actually submit the HTMLForm.
250 * @param string|array $value The value the field was submitted with
251 * @param array $alldata The data collected from the form
253 * @return bool True to cancel the submission
255 function cancelSubmit( $value, $alldata ) {
260 * Override this function to add specific validation checks on the
261 * field input. Don't forget to call parent::validate() to ensure
262 * that the user-defined callback mValidationCallback is still run
264 * @param string|array $value The value the field was submitted with
265 * @param array $alldata The data collected from the form
267 * @return bool|string True on success, or String error to display, or
268 * false to fail validation without displaying an error.
270 function validate( $value, $alldata ) {
271 if ( $this->isHidden( $alldata ) ) {
275 if ( isset( $this->mParams
['required'] )
276 && $this->mParams
['required'] !== false
279 return $this->msg( 'htmlform-required' )->parse();
282 if ( isset( $this->mValidationCallback
) ) {
283 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
289 function filter( $value, $alldata ) {
290 if ( isset( $this->mFilterCallback
) ) {
291 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
298 * Should this field have a label, or is there no input element with the
299 * appropriate id for the label to point to?
301 * @return bool True to output a label, false to suppress
303 protected function needsLabel() {
308 * Tell the field whether to generate a separate label element if its label
313 * @param bool $show Set to false to not generate a label.
316 public function setShowEmptyLabel( $show ) {
317 $this->mShowEmptyLabels
= $show;
321 * Get the value that this input has been set to from a posted form,
322 * or the input's default value if it has not been set.
324 * @param WebRequest $request
325 * @return string The value
327 function loadDataFromRequest( $request ) {
328 if ( $request->getCheck( $this->mName
) ) {
329 return $request->getText( $this->mName
);
331 return $this->getDefault();
336 * Initialise the object
338 * @param array $params Associative Array. See HTMLForm doc for syntax.
340 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
341 * @throws MWException
343 function __construct( $params ) {
344 $this->mParams
= $params;
346 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm
) {
347 $this->mParent
= $params['parent'];
350 # Generate the label from a message, if possible
351 if ( isset( $params['label-message'] ) ) {
352 $msgInfo = $params['label-message'];
354 if ( is_array( $msgInfo ) ) {
355 $msg = array_shift( $msgInfo );
361 $this->mLabel
= $this->msg( $msg, $msgInfo )->parse();
362 } elseif ( isset( $params['label'] ) ) {
363 if ( $params['label'] === ' ' ) {
364 // Apparently some things set   directly and in an odd format
365 $this->mLabel
= ' ';
367 $this->mLabel
= htmlspecialchars( $params['label'] );
369 } elseif ( isset( $params['label-raw'] ) ) {
370 $this->mLabel
= $params['label-raw'];
373 $this->mName
= "wp{$params['fieldname']}";
374 if ( isset( $params['name'] ) ) {
375 $this->mName
= $params['name'];
378 $validName = Sanitizer
::escapeId( $this->mName
);
379 $validName = str_replace( array( '.5B', '.5D' ), array( '[', ']' ), $validName );
380 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
381 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
384 $this->mID
= "mw-input-{$this->mName}";
386 if ( isset( $params['default'] ) ) {
387 $this->mDefault
= $params['default'];
390 if ( isset( $params['id'] ) ) {
392 $validId = Sanitizer
::escapeId( $id );
394 if ( $id != $validId ) {
395 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
401 if ( isset( $params['cssclass'] ) ) {
402 $this->mClass
= $params['cssclass'];
405 if ( isset( $params['csshelpclass'] ) ) {
406 $this->mHelpClass
= $params['csshelpclass'];
409 if ( isset( $params['validation-callback'] ) ) {
410 $this->mValidationCallback
= $params['validation-callback'];
413 if ( isset( $params['filter-callback'] ) ) {
414 $this->mFilterCallback
= $params['filter-callback'];
417 if ( isset( $params['flatlist'] ) ) {
418 $this->mClass
.= ' mw-htmlform-flatlist';
421 if ( isset( $params['hidelabel'] ) ) {
422 $this->mShowEmptyLabels
= false;
425 if ( isset( $params['hide-if'] ) ) {
426 $this->mHideIf
= $params['hide-if'];
431 * Get the complete table row for the input, including help text,
432 * labels, and whatever.
434 * @param string $value The value to set the input to.
436 * @return string Complete HTML table row.
438 function getTableRow( $value ) {
439 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
440 $inputHtml = $this->getInputHTML( $value );
441 $fieldType = get_class( $this );
442 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
443 $cellAttributes = array();
444 $rowAttributes = array();
447 if ( !empty( $this->mParams
['vertical-label'] ) ) {
448 $cellAttributes['colspan'] = 2;
449 $verticalLabel = true;
451 $verticalLabel = false;
454 $label = $this->getLabelHtml( $cellAttributes );
456 $field = Html
::rawElement(
458 array( 'class' => 'mw-input' ) +
$cellAttributes,
459 $inputHtml . "\n$errors"
462 if ( $this->mHideIf
) {
463 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
464 $rowClasses .= ' mw-htmlform-hide-if';
467 if ( $verticalLabel ) {
468 $html = Html
::rawElement( 'tr',
469 $rowAttributes +
array( 'class' => "mw-htmlform-vertical-label $rowClasses" ), $label );
470 $html .= Html
::rawElement( 'tr',
471 $rowAttributes +
array(
472 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
477 Html
::rawElement( 'tr',
478 $rowAttributes +
array(
479 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
484 return $html . $helptext;
488 * Get the complete div for the input, including help text,
489 * labels, and whatever.
492 * @param string $value The value to set the input to.
494 * @return string Complete HTML table row.
496 public function getDiv( $value ) {
497 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
498 $inputHtml = $this->getInputHTML( $value );
499 $fieldType = get_class( $this );
500 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
501 $cellAttributes = array();
502 $label = $this->getLabelHtml( $cellAttributes );
504 $outerDivClass = array(
506 'mw-htmlform-nolabel' => ( $label === '' )
509 $field = Html
::rawElement(
511 array( 'class' => $outerDivClass ) +
$cellAttributes,
512 $inputHtml . "\n$errors"
514 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass
, $errorClass );
515 if ( $this->mParent
->isVForm() ) {
516 $divCssClasses[] = 'mw-ui-vform-field';
519 $wrapperAttributes = array(
520 'class' => $divCssClasses,
522 if ( $this->mHideIf
) {
523 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
524 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
526 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
533 * Get the complete raw fields for the input, including help text,
534 * labels, and whatever.
537 * @param string $value The value to set the input to.
539 * @return string Complete HTML table row.
541 public function getRaw( $value ) {
542 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
543 $inputHtml = $this->getInputHTML( $value );
544 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
545 $cellAttributes = array();
546 $label = $this->getLabelHtml( $cellAttributes );
557 * Generate help text HTML in table format
560 * @param string|null $helptext
563 public function getHelpTextHtmlTable( $helptext ) {
564 if ( is_null( $helptext ) ) {
568 $rowAttributes = array();
569 if ( $this->mHideIf
) {
570 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
571 $rowAttributes['class'] = 'mw-htmlform-hide-if';
574 $tdClasses = array( 'htmlform-tip' );
575 if ( $this->mHelpClass
!== false ) {
576 $tdClasses[] = $this->mHelpClass
;
578 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => $tdClasses ), $helptext );
579 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
585 * Generate help text HTML in div format
588 * @param string|null $helptext
592 public function getHelpTextHtmlDiv( $helptext ) {
593 if ( is_null( $helptext ) ) {
597 $wrapperAttributes = array(
598 'class' => 'htmlform-tip',
600 if ( $this->mHelpClass
!== false ) {
601 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
603 if ( $this->mHideIf
) {
604 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
605 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
607 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
613 * Generate help text HTML formatted for raw output
616 * @param string|null $helptext
619 public function getHelpTextHtmlRaw( $helptext ) {
620 return $this->getHelpTextHtmlDiv( $helptext );
624 * Determine the help text to display
628 public function getHelpText() {
631 if ( isset( $this->mParams
['help-message'] ) ) {
632 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
635 if ( isset( $this->mParams
['help-messages'] ) ) {
636 foreach ( $this->mParams
['help-messages'] as $name ) {
637 $helpMessage = (array)$name;
638 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
640 if ( $msg->exists() ) {
641 if ( is_null( $helptext ) ) {
644 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
646 $helptext .= $msg->parse(); // Append message
649 } elseif ( isset( $this->mParams
['help'] ) ) {
650 $helptext = $this->mParams
['help'];
657 * Determine form errors to display and their classes
660 * @param string $value The value of the input
663 public function getErrorsAndErrorClass( $value ) {
664 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
666 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
670 $errors = self
::formatErrors( $errors );
671 $errorClass = 'mw-htmlform-invalid-input';
674 return array( $errors, $errorClass );
677 function getLabel() {
678 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
681 function getLabelHtml( $cellAttributes = array() ) {
682 # Don't output a for= attribute for labels with no associated input.
683 # Kind of hacky here, possibly we don't want these to be <label>s at all.
686 if ( $this->needsLabel() ) {
687 $for['for'] = $this->mID
;
690 $labelValue = trim( $this->getLabel() );
692 if ( $labelValue !== ' ' && $labelValue !== '' ) {
696 $displayFormat = $this->mParent
->getDisplayFormat();
699 if ( $displayFormat === 'table' ) {
701 Html
::rawElement( 'td',
702 array( 'class' => 'mw-label' ) +
$cellAttributes,
703 Html
::rawElement( 'label', $for, $labelValue ) );
704 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
705 if ( $displayFormat === 'div' ) {
707 Html
::rawElement( 'div',
708 array( 'class' => 'mw-label' ) +
$cellAttributes,
709 Html
::rawElement( 'label', $for, $labelValue ) );
711 $html = Html
::rawElement( 'label', $for, $labelValue );
718 function getDefault() {
719 if ( isset( $this->mDefault
) ) {
720 return $this->mDefault
;
727 * Returns the attributes required for the tooltip and accesskey.
729 * @return array Attributes
731 public function getTooltipAndAccessKey() {
732 if ( empty( $this->mParams
['tooltip'] ) ) {
736 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
740 * Returns the given attributes from the parameters
742 * @param array $list List of attributes to get
743 * @return array Attributes
745 public function getAttributes( array $list ) {
746 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
750 foreach ( $list as $key ) {
751 if ( in_array( $key, $boolAttribs ) ) {
752 if ( !empty( $this->mParams
[$key] ) ) {
755 } elseif ( isset( $this->mParams
[$key] ) ) {
756 $ret[$key] = $this->mParams
[$key];
764 * Given an array of msg-key => value mappings, returns an array with keys
765 * being the message texts. It also forces values to strings.
767 * @param array $options
770 private function lookupOptionsKeys( $options ) {
772 foreach ( $options as $key => $value ) {
773 $key = $this->msg( $key )->plain();
774 $ret[$key] = is_array( $value )
775 ?
$this->lookupOptionsKeys( $value )
782 * Recursively forces values in an array to strings, because issues arise
783 * with integer 0 as a value.
785 * @param array $array
788 static function forceToStringRecursive( $array ) {
789 if ( is_array( $array ) ) {
790 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
792 return strval( $array );
797 * Fetch the array of options from the field's parameters. In order, this
798 * checks 'options-messages', 'options', then 'options-message'.
800 * @return array|null Options array
802 public function getOptions() {
803 if ( $this->mOptions
=== false ) {
804 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
805 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
806 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
807 $this->mOptionsLabelsNotFromMessage
= true;
808 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
809 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
810 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
811 $message = $this->msg( $this->mParams
['options-message'] )->inContentLanguage()->plain();
814 $this->mOptions
= array();
815 foreach ( explode( "\n", $message ) as $option ) {
816 $value = trim( $option );
817 if ( $value == '' ) {
819 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
820 # A new group is starting...
821 $value = trim( substr( $value, 1 ) );
823 } elseif ( substr( $value, 0, 2 ) == '**' ) {
825 $opt = trim( substr( $value, 2 ) );
826 if ( $optgroup === false ) {
827 $this->mOptions
[$opt] = $opt;
829 $this->mOptions
[$optgroup][$opt] = $opt;
832 # groupless reason list
834 $this->mOptions
[$option] = $option;
838 $this->mOptions
= null;
842 return $this->mOptions
;
846 * flatten an array of options to a single array, for instance,
847 * a set of "<options>" inside "<optgroups>".
849 * @param array $options Associative Array with values either Strings or Arrays
850 * @return array Flattened input
852 public static function flattenOptions( $options ) {
855 foreach ( $options as $value ) {
856 if ( is_array( $value ) ) {
857 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
859 $flatOpts[] = $value;
867 * Formats one or more errors as accepted by field validation-callback.
869 * @param string|Message|array $errors Array of strings or Message instances
870 * @return string HTML
873 protected static function formatErrors( $errors ) {
874 if ( is_array( $errors ) && count( $errors ) === 1 ) {
875 $errors = array_shift( $errors );
878 if ( is_array( $errors ) ) {
880 foreach ( $errors as $error ) {
881 if ( $error instanceof Message
) {
882 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
884 $lines[] = Html
::rawElement( 'li', array(), $error );
888 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
890 if ( $errors instanceof Message
) {
891 $errors = $errors->parse();
894 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );