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 $mVFormClass = '';
17 protected $mHelpClass = false;
19 protected $mOptions = false;
20 protected $mOptionsLabelsNotFromMessage = false;
21 protected $mHideIf = null;
24 * @var bool If true will generate an empty div element with no label
27 protected $mShowEmptyLabels = true;
35 * This function must be implemented to return the HTML to generate
36 * the input object itself. It should not implement the surrounding
37 * table cells/rows, or labels/help messages.
39 * @param string $value The value to set the input to; eg a default
40 * text for a text input.
42 * @return string Valid HTML.
44 abstract function getInputHTML( $value );
47 * Get a translated interface message
49 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
50 * and wfMessage() otherwise.
52 * Parameters are the same as wfMessage().
57 $args = func_get_args();
59 if ( $this->mParent
) {
60 $callback = array( $this->mParent
, 'msg' );
62 $callback = 'wfMessage';
65 return call_user_func_array( $callback, $args );
70 * Fetch a field value from $alldata for the closest field matching a given
73 * This is complex because it needs to handle array fields like the user
74 * would expect. The general algorithm is to look for $name as a sibling
75 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
76 * that $name itself might be referencing an array.
78 * @param array $alldata
82 protected function getNearestFieldByName( $alldata, $name ) {
85 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
86 array_unshift( $thisKeys, $m[2] );
89 if ( substr( $tmp, 0, 2 ) == 'wp' &&
90 !isset( $alldata[$tmp] ) &&
91 isset( $alldata[substr( $tmp, 2 )] )
93 // Adjust for name mangling.
94 $tmp = substr( $tmp, 2 );
96 array_unshift( $thisKeys, $tmp );
100 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
101 array_unshift( $nameKeys, $m[2] );
104 array_unshift( $nameKeys, $tmp );
107 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
108 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
111 $key = array_shift( $keys );
112 if ( !is_array( $data ) ||
!isset( $data[$key] ) ) {
117 $testValue = (string)$data;
125 * Helper function for isHidden to handle recursive data structures.
127 * @param array $alldata
128 * @param array $params
130 * @throws MWException
132 protected function isHiddenRecurse( array $alldata, array $params ) {
133 $origParams = $params;
134 $op = array_shift( $params );
139 foreach ( $params as $i => $p ) {
140 if ( !is_array( $p ) ) {
141 throw new MWException(
142 "Expected array, found " . gettype( $p ) . " at index $i"
145 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
152 foreach ( $params as $p ) {
153 if ( !is_array( $p ) ) {
154 throw new MWException(
155 "Expected array, found " . gettype( $p ) . " at index $i"
158 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
165 foreach ( $params as $i => $p ) {
166 if ( !is_array( $p ) ) {
167 throw new MWException(
168 "Expected array, found " . gettype( $p ) . " at index $i"
171 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
178 foreach ( $params as $p ) {
179 if ( !is_array( $p ) ) {
180 throw new MWException(
181 "Expected array, found " . gettype( $p ) . " at index $i"
184 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
191 if ( count( $params ) !== 1 ) {
192 throw new MWException( "NOT takes exactly one parameter" );
195 if ( !is_array( $p ) ) {
196 throw new MWException(
197 "Expected array, found " . gettype( $p ) . " at index 0"
200 return !$this->isHiddenRecurse( $alldata, $p );
204 if ( count( $params ) !== 2 ) {
205 throw new MWException( "$op takes exactly two parameters" );
207 list( $field, $value ) = $params;
208 if ( !is_string( $field ) ||
!is_string( $value ) ) {
209 throw new MWException( "Parameters for $op must be strings" );
211 $testValue = $this->getNearestFieldByName( $alldata, $field );
214 return ( $value === $testValue );
216 return ( $value !== $testValue );
220 throw new MWException( "Unknown operation" );
222 } catch ( Exception
$ex ) {
223 throw new MWException(
224 "Invalid hide-if specification for $this->mName: " .
225 $ex->getMessage() . " in " . var_export( $origParams, true ),
232 * Test whether this field is supposed to be hidden, based on the values of
233 * the other form fields.
236 * @param array $alldata The data collected from the form
239 function isHidden( $alldata ) {
240 if ( !$this->mHideIf
) {
244 return $this->isHiddenRecurse( $alldata, $this->mHideIf
);
248 * Override this function if the control can somehow trigger a form
249 * submission that shouldn't actually submit the HTMLForm.
252 * @param string|array $value The value the field was submitted with
253 * @param array $alldata The data collected from the form
255 * @return bool True to cancel the submission
257 function cancelSubmit( $value, $alldata ) {
262 * Override this function to add specific validation checks on the
263 * field input. Don't forget to call parent::validate() to ensure
264 * that the user-defined callback mValidationCallback is still run
266 * @param string|array $value The value the field was submitted with
267 * @param array $alldata The data collected from the form
269 * @return bool|string True on success, or String error to display, or
270 * false to fail validation without displaying an error.
272 function validate( $value, $alldata ) {
273 if ( $this->isHidden( $alldata ) ) {
277 if ( isset( $this->mParams
['required'] )
278 && $this->mParams
['required'] !== false
281 return $this->msg( 'htmlform-required' )->parse();
284 if ( isset( $this->mValidationCallback
) ) {
285 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
291 function filter( $value, $alldata ) {
292 if ( isset( $this->mFilterCallback
) ) {
293 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
300 * Should this field have a label, or is there no input element with the
301 * appropriate id for the label to point to?
303 * @return bool True to output a label, false to suppress
305 protected function needsLabel() {
310 * Tell the field whether to generate a separate label element if its label
315 * @param bool $show Set to false to not generate a label.
318 public function setShowEmptyLabel( $show ) {
319 $this->mShowEmptyLabels
= $show;
323 * Get the value that this input has been set to from a posted form,
324 * or the input's default value if it has not been set.
326 * @param WebRequest $request
327 * @return string The value
329 function loadDataFromRequest( $request ) {
330 if ( $request->getCheck( $this->mName
) ) {
331 return $request->getText( $this->mName
);
333 return $this->getDefault();
338 * Initialise the object
340 * @param array $params Associative Array. See HTMLForm doc for syntax.
342 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
343 * @throws MWException
345 function __construct( $params ) {
346 $this->mParams
= $params;
348 if ( isset( $params['parent'] ) && $params['parent'] instanceof HTMLForm
) {
349 $this->mParent
= $params['parent'];
352 # Generate the label from a message, if possible
353 if ( isset( $params['label-message'] ) ) {
354 $msgInfo = $params['label-message'];
356 if ( is_array( $msgInfo ) ) {
357 $msg = array_shift( $msgInfo );
363 $this->mLabel
= $this->msg( $msg, $msgInfo )->parse();
364 } elseif ( isset( $params['label'] ) ) {
365 if ( $params['label'] === ' ' ) {
366 // Apparently some things set   directly and in an odd format
367 $this->mLabel
= ' ';
369 $this->mLabel
= htmlspecialchars( $params['label'] );
371 } elseif ( isset( $params['label-raw'] ) ) {
372 $this->mLabel
= $params['label-raw'];
375 $this->mName
= "wp{$params['fieldname']}";
376 if ( isset( $params['name'] ) ) {
377 $this->mName
= $params['name'];
380 $validName = Sanitizer
::escapeId( $this->mName
);
381 $validName = str_replace( array( '.5B', '.5D' ), array( '[', ']' ), $validName );
382 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
383 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
386 $this->mID
= "mw-input-{$this->mName}";
388 if ( isset( $params['default'] ) ) {
389 $this->mDefault
= $params['default'];
392 if ( isset( $params['id'] ) ) {
394 $validId = Sanitizer
::escapeId( $id );
396 if ( $id != $validId ) {
397 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
403 if ( isset( $params['cssclass'] ) ) {
404 $this->mClass
= $params['cssclass'];
407 if ( isset( $params['csshelpclass'] ) ) {
408 $this->mHelpClass
= $params['csshelpclass'];
411 if ( isset( $params['validation-callback'] ) ) {
412 $this->mValidationCallback
= $params['validation-callback'];
415 if ( isset( $params['filter-callback'] ) ) {
416 $this->mFilterCallback
= $params['filter-callback'];
419 if ( isset( $params['flatlist'] ) ) {
420 $this->mClass
.= ' mw-htmlform-flatlist';
423 if ( isset( $params['hidelabel'] ) ) {
424 $this->mShowEmptyLabels
= false;
427 if ( isset( $params['hide-if'] ) ) {
428 $this->mHideIf
= $params['hide-if'];
433 * Get the complete table row for the input, including help text,
434 * labels, and whatever.
436 * @param string $value The value to set the input to.
438 * @return string Complete HTML table row.
440 function getTableRow( $value ) {
441 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
442 $inputHtml = $this->getInputHTML( $value );
443 $fieldType = get_class( $this );
444 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
445 $cellAttributes = array();
446 $rowAttributes = array();
449 if ( !empty( $this->mParams
['vertical-label'] ) ) {
450 $cellAttributes['colspan'] = 2;
451 $verticalLabel = true;
453 $verticalLabel = false;
456 $label = $this->getLabelHtml( $cellAttributes );
458 $field = Html
::rawElement(
460 array( 'class' => 'mw-input' ) +
$cellAttributes,
461 $inputHtml . "\n$errors"
464 if ( $this->mHideIf
) {
465 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
466 $rowClasses .= ' mw-htmlform-hide-if';
469 if ( $verticalLabel ) {
470 $html = Html
::rawElement( 'tr',
471 $rowAttributes +
array( 'class' => "mw-htmlform-vertical-label $rowClasses" ), $label );
472 $html .= Html
::rawElement( 'tr',
473 $rowAttributes +
array(
474 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
479 Html
::rawElement( 'tr',
480 $rowAttributes +
array(
481 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
486 return $html . $helptext;
490 * Get the complete div for the input, including help text,
491 * labels, and whatever.
494 * @param string $value The value to set the input to.
496 * @return string Complete HTML table row.
498 public function getDiv( $value ) {
499 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
500 $inputHtml = $this->getInputHTML( $value );
501 $fieldType = get_class( $this );
502 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
503 $cellAttributes = array();
504 $label = $this->getLabelHtml( $cellAttributes );
506 $outerDivClass = array(
508 'mw-htmlform-nolabel' => ( $label === '' )
511 $field = Html
::rawElement(
513 array( 'class' => $outerDivClass ) +
$cellAttributes,
514 $inputHtml . "\n$errors"
516 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass
, $this->mVFormClass
, $errorClass );
518 $wrapperAttributes = array(
519 'class' => $divCssClasses,
521 if ( $this->mHideIf
) {
522 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
523 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
525 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
532 * Get the complete raw fields for the input, including help text,
533 * labels, and whatever.
536 * @param string $value The value to set the input to.
538 * @return string Complete HTML table row.
540 public function getRaw( $value ) {
541 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
542 $inputHtml = $this->getInputHTML( $value );
543 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
544 $cellAttributes = array();
545 $label = $this->getLabelHtml( $cellAttributes );
556 * Get the complete field for the input, including help text,
557 * labels, and whatever. Fall back from 'vform' to 'div' when not overridden.
560 * @param string $value The value to set the input to.
561 * @return string Complete HTML field.
563 public function getVForm( $value ) {
565 $this->mVFormClass
= ' mw-ui-vform-field';
566 return $this->getDiv( $value );
570 * Generate help text HTML in table format
573 * @param string|null $helptext
576 public function getHelpTextHtmlTable( $helptext ) {
577 if ( is_null( $helptext ) ) {
581 $rowAttributes = array();
582 if ( $this->mHideIf
) {
583 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
584 $rowAttributes['class'] = 'mw-htmlform-hide-if';
587 $tdClasses = array( 'htmlform-tip' );
588 if ( $this->mHelpClass
!== false ) {
589 $tdClasses[] = $this->mHelpClass
;
591 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => $tdClasses ), $helptext );
592 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
598 * Generate help text HTML in div format
601 * @param string|null $helptext
605 public function getHelpTextHtmlDiv( $helptext ) {
606 if ( is_null( $helptext ) ) {
610 $wrapperAttributes = array(
611 'class' => 'htmlform-tip',
613 if ( $this->mHelpClass
!== false ) {
614 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
616 if ( $this->mHideIf
) {
617 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
618 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
620 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
626 * Generate help text HTML formatted for raw output
629 * @param string|null $helptext
632 public function getHelpTextHtmlRaw( $helptext ) {
633 return $this->getHelpTextHtmlDiv( $helptext );
637 * Determine the help text to display
641 public function getHelpText() {
644 if ( isset( $this->mParams
['help-message'] ) ) {
645 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
648 if ( isset( $this->mParams
['help-messages'] ) ) {
649 foreach ( $this->mParams
['help-messages'] as $name ) {
650 $helpMessage = (array)$name;
651 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
653 if ( $msg->exists() ) {
654 if ( is_null( $helptext ) ) {
657 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
659 $helptext .= $msg->parse(); // Append message
662 } elseif ( isset( $this->mParams
['help'] ) ) {
663 $helptext = $this->mParams
['help'];
670 * Determine form errors to display and their classes
673 * @param string $value The value of the input
676 public function getErrorsAndErrorClass( $value ) {
677 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
679 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
683 $errors = self
::formatErrors( $errors );
684 $errorClass = 'mw-htmlform-invalid-input';
687 return array( $errors, $errorClass );
690 function getLabel() {
691 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
694 function getLabelHtml( $cellAttributes = array() ) {
695 # Don't output a for= attribute for labels with no associated input.
696 # Kind of hacky here, possibly we don't want these to be <label>s at all.
699 if ( $this->needsLabel() ) {
700 $for['for'] = $this->mID
;
703 $labelValue = trim( $this->getLabel() );
705 if ( $labelValue !== ' ' && $labelValue !== '' ) {
709 $displayFormat = $this->mParent
->getDisplayFormat();
712 if ( $displayFormat === 'table' ) {
714 Html
::rawElement( 'td',
715 array( 'class' => 'mw-label' ) +
$cellAttributes,
716 Html
::rawElement( 'label', $for, $labelValue ) );
717 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
718 if ( $displayFormat === 'div' ) {
720 Html
::rawElement( 'div',
721 array( 'class' => 'mw-label' ) +
$cellAttributes,
722 Html
::rawElement( 'label', $for, $labelValue ) );
724 $html = Html
::rawElement( 'label', $for, $labelValue );
731 function getDefault() {
732 if ( isset( $this->mDefault
) ) {
733 return $this->mDefault
;
740 * Returns the attributes required for the tooltip and accesskey.
742 * @return array Attributes
744 public function getTooltipAndAccessKey() {
745 if ( empty( $this->mParams
['tooltip'] ) ) {
749 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
753 * Returns the given attributes from the parameters
755 * @param array $list List of attributes to get
756 * @return array Attributes
758 public function getAttributes( array $list ) {
759 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
763 foreach ( $list as $key ) {
764 if ( in_array( $key, $boolAttribs ) ) {
765 if ( !empty( $this->mParams
[$key] ) ) {
768 } elseif ( isset( $this->mParams
[$key] ) ) {
769 $ret[$key] = $this->mParams
[$key];
777 * Given an array of msg-key => value mappings, returns an array with keys
778 * being the message texts. It also forces values to strings.
780 * @param array $options
783 private function lookupOptionsKeys( $options ) {
785 foreach ( $options as $key => $value ) {
786 $key = $this->msg( $key )->plain();
787 $ret[$key] = is_array( $value )
788 ?
$this->lookupOptionsKeys( $value )
795 * Recursively forces values in an array to strings, because issues arise
796 * with integer 0 as a value.
798 * @param array $array
801 static function forceToStringRecursive( $array ) {
802 if ( is_array( $array ) ) {
803 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
805 return strval( $array );
810 * Fetch the array of options from the field's parameters. In order, this
811 * checks 'options-messages', 'options', then 'options-message'.
813 * @return array|null Options array
815 public function getOptions() {
816 if ( $this->mOptions
=== false ) {
817 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
818 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
819 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
820 $this->mOptionsLabelsNotFromMessage
= true;
821 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
822 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
823 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
824 $message = $this->msg( $this->mParams
['options-message'] )->inContentLanguage()->plain();
827 $this->mOptions
= array();
828 foreach ( explode( "\n", $message ) as $option ) {
829 $value = trim( $option );
830 if ( $value == '' ) {
832 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
833 # A new group is starting...
834 $value = trim( substr( $value, 1 ) );
836 } elseif ( substr( $value, 0, 2 ) == '**' ) {
838 $opt = trim( substr( $value, 2 ) );
839 if ( $optgroup === false ) {
840 $this->mOptions
[$opt] = $opt;
842 $this->mOptions
[$optgroup][$opt] = $opt;
845 # groupless reason list
847 $this->mOptions
[$option] = $option;
851 $this->mOptions
= null;
855 return $this->mOptions
;
859 * flatten an array of options to a single array, for instance,
860 * a set of "<options>" inside "<optgroups>".
862 * @param array $options Associative Array with values either Strings or Arrays
863 * @return array Flattened input
865 public static function flattenOptions( $options ) {
868 foreach ( $options as $value ) {
869 if ( is_array( $value ) ) {
870 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
872 $flatOpts[] = $value;
880 * Formats one or more errors as accepted by field validation-callback.
882 * @param string|Message|array $errors Array of strings or Message instances
883 * @return string HTML
886 protected static function formatErrors( $errors ) {
887 if ( is_array( $errors ) && count( $errors ) === 1 ) {
888 $errors = array_shift( $errors );
891 if ( is_array( $errors ) ) {
893 foreach ( $errors as $error ) {
894 if ( $error instanceof Message
) {
895 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
897 $lines[] = Html
::rawElement( 'li', array(), $error );
901 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
903 if ( $errors instanceof Message
) {
904 $errors = $errors->parse();
907 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );