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 ( MWException
$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 );
516 if ( $this->mParent
->isVForm() ) {
517 $divCssClasses[] = 'mw-ui-vform-field';
520 $wrapperAttributes = array(
521 'class' => $divCssClasses,
523 if ( $this->mHideIf
) {
524 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
525 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
527 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
534 * Get the complete raw fields for the input, including help text,
535 * labels, and whatever.
538 * @param string $value The value to set the input to.
540 * @return string Complete HTML table row.
542 public function getRaw( $value ) {
543 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
544 $inputHtml = $this->getInputHTML( $value );
545 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
546 $cellAttributes = array();
547 $label = $this->getLabelHtml( $cellAttributes );
558 * Generate help text HTML in table format
561 * @param string|null $helptext
564 public function getHelpTextHtmlTable( $helptext ) {
565 if ( is_null( $helptext ) ) {
569 $rowAttributes = array();
570 if ( $this->mHideIf
) {
571 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
572 $rowAttributes['class'] = 'mw-htmlform-hide-if';
575 $tdClasses = array( 'htmlform-tip' );
576 if ( $this->mHelpClass
!== false ) {
577 $tdClasses[] = $this->mHelpClass
;
579 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => $tdClasses ), $helptext );
580 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
586 * Generate help text HTML in div format
589 * @param string|null $helptext
593 public function getHelpTextHtmlDiv( $helptext ) {
594 if ( is_null( $helptext ) ) {
598 $wrapperAttributes = array(
599 'class' => 'htmlform-tip',
601 if ( $this->mHelpClass
!== false ) {
602 $wrapperAttributes['class'] .= " {$this->mHelpClass}";
604 if ( $this->mHideIf
) {
605 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
606 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
608 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
614 * Generate help text HTML formatted for raw output
617 * @param string|null $helptext
620 public function getHelpTextHtmlRaw( $helptext ) {
621 return $this->getHelpTextHtmlDiv( $helptext );
625 * Determine the help text to display
629 public function getHelpText() {
632 if ( isset( $this->mParams
['help-message'] ) ) {
633 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
636 if ( isset( $this->mParams
['help-messages'] ) ) {
637 foreach ( $this->mParams
['help-messages'] as $name ) {
638 $helpMessage = (array)$name;
639 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
641 if ( $msg->exists() ) {
642 if ( is_null( $helptext ) ) {
645 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
647 $helptext .= $msg->parse(); // Append message
650 } elseif ( isset( $this->mParams
['help'] ) ) {
651 $helptext = $this->mParams
['help'];
658 * Determine form errors to display and their classes
661 * @param string $value The value of the input
664 public function getErrorsAndErrorClass( $value ) {
665 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
667 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
671 $errors = self
::formatErrors( $errors );
672 $errorClass = 'mw-htmlform-invalid-input';
675 return array( $errors, $errorClass );
678 function getLabel() {
679 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
682 function getLabelHtml( $cellAttributes = array() ) {
683 # Don't output a for= attribute for labels with no associated input.
684 # Kind of hacky here, possibly we don't want these to be <label>s at all.
687 if ( $this->needsLabel() ) {
688 $for['for'] = $this->mID
;
691 $labelValue = trim( $this->getLabel() );
693 if ( $labelValue !== ' ' && $labelValue !== '' ) {
697 $displayFormat = $this->mParent
->getDisplayFormat();
700 if ( $displayFormat === 'table' ) {
702 Html
::rawElement( 'td',
703 array( 'class' => 'mw-label' ) +
$cellAttributes,
704 Html
::rawElement( 'label', $for, $labelValue ) );
705 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
706 if ( $displayFormat === 'div' ) {
708 Html
::rawElement( 'div',
709 array( 'class' => 'mw-label' ) +
$cellAttributes,
710 Html
::rawElement( 'label', $for, $labelValue ) );
712 $html = Html
::rawElement( 'label', $for, $labelValue );
719 function getDefault() {
720 if ( isset( $this->mDefault
) ) {
721 return $this->mDefault
;
728 * Returns the attributes required for the tooltip and accesskey.
730 * @return array Attributes
732 public function getTooltipAndAccessKey() {
733 if ( empty( $this->mParams
['tooltip'] ) ) {
737 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
741 * Returns the given attributes from the parameters
743 * @param array $list List of attributes to get
744 * @return array Attributes
746 public function getAttributes( array $list ) {
747 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
751 foreach ( $list as $key ) {
752 if ( in_array( $key, $boolAttribs ) ) {
753 if ( !empty( $this->mParams
[$key] ) ) {
756 } elseif ( isset( $this->mParams
[$key] ) ) {
757 $ret[$key] = $this->mParams
[$key];
765 * Given an array of msg-key => value mappings, returns an array with keys
766 * being the message texts. It also forces values to strings.
768 * @param array $options
771 private function lookupOptionsKeys( $options ) {
773 foreach ( $options as $key => $value ) {
774 $key = $this->msg( $key )->plain();
775 $ret[$key] = is_array( $value )
776 ?
$this->lookupOptionsKeys( $value )
783 * Recursively forces values in an array to strings, because issues arise
784 * with integer 0 as a value.
786 * @param array $array
789 static function forceToStringRecursive( $array ) {
790 if ( is_array( $array ) ) {
791 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
793 return strval( $array );
798 * Fetch the array of options from the field's parameters. In order, this
799 * checks 'options-messages', 'options', then 'options-message'.
801 * @return array|null Options array
803 public function getOptions() {
804 if ( $this->mOptions
=== false ) {
805 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
806 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
807 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
808 $this->mOptionsLabelsNotFromMessage
= true;
809 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
810 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
811 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
812 $message = $this->msg( $this->mParams
['options-message'] )->inContentLanguage()->plain();
815 $this->mOptions
= array();
816 foreach ( explode( "\n", $message ) as $option ) {
817 $value = trim( $option );
818 if ( $value == '' ) {
820 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
821 # A new group is starting...
822 $value = trim( substr( $value, 1 ) );
824 } elseif ( substr( $value, 0, 2 ) == '**' ) {
826 $opt = trim( substr( $value, 2 ) );
827 if ( $optgroup === false ) {
828 $this->mOptions
[$opt] = $opt;
830 $this->mOptions
[$optgroup][$opt] = $opt;
833 # groupless reason list
835 $this->mOptions
[$option] = $option;
839 $this->mOptions
= null;
843 return $this->mOptions
;
847 * flatten an array of options to a single array, for instance,
848 * a set of "<options>" inside "<optgroups>".
850 * @param array $options Associative Array with values either Strings or Arrays
851 * @return array Flattened input
853 public static function flattenOptions( $options ) {
856 foreach ( $options as $value ) {
857 if ( is_array( $value ) ) {
858 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
860 $flatOpts[] = $value;
868 * Formats one or more errors as accepted by field validation-callback.
870 * @param string|Message|array $errors Array of strings or Message instances
871 * @return string HTML
874 protected static function formatErrors( $errors ) {
875 if ( is_array( $errors ) && count( $errors ) === 1 ) {
876 $errors = array_shift( $errors );
879 if ( is_array( $errors ) ) {
881 foreach ( $errors as $error ) {
882 if ( $error instanceof Message
) {
883 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
885 $lines[] = Html
::rawElement( 'li', array(), $error );
889 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
891 if ( $errors instanceof Message
) {
892 $errors = $errors->parse();
895 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );