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] ) ) {
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 # Generate the label from a message, if possible
347 if ( isset( $params['label-message'] ) ) {
348 $msgInfo = $params['label-message'];
350 if ( is_array( $msgInfo ) ) {
351 $msg = array_shift( $msgInfo );
357 $this->mLabel
= wfMessage( $msg, $msgInfo )->parse();
358 } elseif ( isset( $params['label'] ) ) {
359 if ( $params['label'] === ' ' ) {
360 // Apparently some things set   directly and in an odd format
361 $this->mLabel
= ' ';
363 $this->mLabel
= htmlspecialchars( $params['label'] );
365 } elseif ( isset( $params['label-raw'] ) ) {
366 $this->mLabel
= $params['label-raw'];
369 $this->mName
= "wp{$params['fieldname']}";
370 if ( isset( $params['name'] ) ) {
371 $this->mName
= $params['name'];
374 $validName = Sanitizer
::escapeId( $this->mName
);
375 $validName = str_replace( array( '.5B', '.5D' ), array( '[', ']' ), $validName );
376 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
377 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
380 $this->mID
= "mw-input-{$this->mName}";
382 if ( isset( $params['default'] ) ) {
383 $this->mDefault
= $params['default'];
386 if ( isset( $params['id'] ) ) {
388 $validId = Sanitizer
::escapeId( $id );
390 if ( $id != $validId ) {
391 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
397 if ( isset( $params['cssclass'] ) ) {
398 $this->mClass
= $params['cssclass'];
401 if ( isset( $params['csshelpclass'] ) ) {
402 $this->mHelpClass
= $params['csshelpclass'];
405 if ( isset( $params['validation-callback'] ) ) {
406 $this->mValidationCallback
= $params['validation-callback'];
409 if ( isset( $params['filter-callback'] ) ) {
410 $this->mFilterCallback
= $params['filter-callback'];
413 if ( isset( $params['flatlist'] ) ) {
414 $this->mClass
.= ' mw-htmlform-flatlist';
417 if ( isset( $params['hidelabel'] ) ) {
418 $this->mShowEmptyLabels
= false;
421 if ( isset( $params['hide-if'] ) ) {
422 $this->mHideIf
= $params['hide-if'];
427 * Get the complete table row for the input, including help text,
428 * labels, and whatever.
430 * @param string $value The value to set the input to.
432 * @return string Complete HTML table row.
434 function getTableRow( $value ) {
435 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
436 $inputHtml = $this->getInputHTML( $value );
437 $fieldType = get_class( $this );
438 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
439 $cellAttributes = array();
440 $rowAttributes = array();
443 if ( !empty( $this->mParams
['vertical-label'] ) ) {
444 $cellAttributes['colspan'] = 2;
445 $verticalLabel = true;
447 $verticalLabel = false;
450 $label = $this->getLabelHtml( $cellAttributes );
452 $field = Html
::rawElement(
454 array( 'class' => 'mw-input' ) +
$cellAttributes,
455 $inputHtml . "\n$errors"
458 if ( $this->mHideIf
) {
459 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
460 $rowClasses .= ' mw-htmlform-hide-if';
463 if ( $verticalLabel ) {
464 $html = Html
::rawElement( 'tr',
465 $rowAttributes +
array( 'class' => "mw-htmlform-vertical-label $rowClasses" ), $label );
466 $html .= Html
::rawElement( 'tr',
467 $rowAttributes +
array(
468 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
473 Html
::rawElement( 'tr',
474 $rowAttributes +
array(
475 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
480 return $html . $helptext;
484 * Get the complete div for the input, including help text,
485 * labels, and whatever.
488 * @param string $value The value to set the input to.
490 * @return string Complete HTML table row.
492 public function getDiv( $value ) {
493 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
494 $inputHtml = $this->getInputHTML( $value );
495 $fieldType = get_class( $this );
496 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
497 $cellAttributes = array();
498 $label = $this->getLabelHtml( $cellAttributes );
500 $outerDivClass = array(
502 'mw-htmlform-nolabel' => ( $label === '' )
505 $field = Html
::rawElement(
507 array( 'class' => $outerDivClass ) +
$cellAttributes,
508 $inputHtml . "\n$errors"
510 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass
, $errorClass );
511 if ( $this->mParent
->isVForm() ) {
512 $divCssClasses[] = 'mw-ui-vform-field';
515 $wrapperAttributes = array(
516 'class' => $divCssClasses,
518 if ( $this->mHideIf
) {
519 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
520 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
522 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
529 * Get the complete raw fields for the input, including help text,
530 * labels, and whatever.
533 * @param string $value The value to set the input to.
535 * @return string Complete HTML table row.
537 public function getRaw( $value ) {
538 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
539 $inputHtml = $this->getInputHTML( $value );
540 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
541 $cellAttributes = array();
542 $label = $this->getLabelHtml( $cellAttributes );
553 * Generate help text HTML in table format
556 * @param string|null $helptext
559 public function getHelpTextHtmlTable( $helptext ) {
560 if ( is_null( $helptext ) ) {
564 $rowAttributes = array();
565 if ( $this->mHideIf
) {
566 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
567 $rowAttributes['class'] = 'mw-htmlform-hide-if';
570 $tdClasses = array( 'htmlform-tip' );
571 if ( $this->mHelpClass
!== false ) {
572 $tdClasses[] = $this->mHelpClass
;
574 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => $tdClasses ), $helptext );
575 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
581 * Generate help text HTML in div format
584 * @param string|null $helptext
588 public function getHelpTextHtmlDiv( $helptext ) {
589 if ( is_null( $helptext ) ) {
593 $wrapperAttributes = array(
594 'class' => 'htmlform-tip',
596 if ( $this->mHideIf
) {
597 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
598 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
600 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
606 * Generate help text HTML formatted for raw output
609 * @param string|null $helptext
612 public function getHelpTextHtmlRaw( $helptext ) {
613 return $this->getHelpTextHtmlDiv( $helptext );
617 * Determine the help text to display
621 public function getHelpText() {
624 if ( isset( $this->mParams
['help-message'] ) ) {
625 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
628 if ( isset( $this->mParams
['help-messages'] ) ) {
629 foreach ( $this->mParams
['help-messages'] as $name ) {
630 $helpMessage = (array)$name;
631 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
633 if ( $msg->exists() ) {
634 if ( is_null( $helptext ) ) {
637 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
639 $helptext .= $msg->parse(); // Append message
642 } elseif ( isset( $this->mParams
['help'] ) ) {
643 $helptext = $this->mParams
['help'];
650 * Determine form errors to display and their classes
653 * @param string $value The value of the input
656 public function getErrorsAndErrorClass( $value ) {
657 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
659 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
663 $errors = self
::formatErrors( $errors );
664 $errorClass = 'mw-htmlform-invalid-input';
667 return array( $errors, $errorClass );
670 function getLabel() {
671 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
674 function getLabelHtml( $cellAttributes = array() ) {
675 # Don't output a for= attribute for labels with no associated input.
676 # Kind of hacky here, possibly we don't want these to be <label>s at all.
679 if ( $this->needsLabel() ) {
680 $for['for'] = $this->mID
;
683 $labelValue = trim( $this->getLabel() );
685 if ( $labelValue !== ' ' && $labelValue !== '' ) {
689 $displayFormat = $this->mParent
->getDisplayFormat();
692 if ( $displayFormat === 'table' ) {
694 Html
::rawElement( 'td',
695 array( 'class' => 'mw-label' ) +
$cellAttributes,
696 Html
::rawElement( 'label', $for, $labelValue ) );
697 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
698 if ( $displayFormat === 'div' ) {
700 Html
::rawElement( 'div',
701 array( 'class' => 'mw-label' ) +
$cellAttributes,
702 Html
::rawElement( 'label', $for, $labelValue ) );
704 $html = Html
::rawElement( 'label', $for, $labelValue );
711 function getDefault() {
712 if ( isset( $this->mDefault
) ) {
713 return $this->mDefault
;
720 * Returns the attributes required for the tooltip and accesskey.
722 * @return array Attributes
724 public function getTooltipAndAccessKey() {
725 if ( empty( $this->mParams
['tooltip'] ) ) {
729 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
733 * Returns the given attributes from the parameters
735 * @param array $list List of attributes to get
736 * @return array Attributes
738 public function getAttributes( array $list ) {
739 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
743 foreach ( $list as $key ) {
744 if ( in_array( $key, $boolAttribs ) ) {
745 if ( !empty( $this->mParams
[$key] ) ) {
748 } elseif ( isset( $this->mParams
[$key] ) ) {
749 $ret[$key] = $this->mParams
[$key];
757 * Given an array of msg-key => value mappings, returns an array with keys
758 * being the message texts. It also forces values to strings.
760 * @param array $options
763 private function lookupOptionsKeys( $options ) {
765 foreach ( $options as $key => $value ) {
766 $key = $this->msg( $key )->plain();
767 $ret[$key] = is_array( $value )
768 ?
$this->lookupOptionsKeys( $value )
775 * Recursively forces values in an array to strings, because issues arise
776 * with integer 0 as a value.
778 * @param array $array
781 static function forceToStringRecursive( $array ) {
782 if ( is_array( $array ) ) {
783 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
785 return strval( $array );
790 * Fetch the array of options from the field's parameters. In order, this
791 * checks 'options-messages', 'options', then 'options-message'.
793 * @return array|null Options array
795 public function getOptions() {
796 if ( $this->mOptions
=== false ) {
797 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
798 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
799 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
800 $this->mOptionsLabelsNotFromMessage
= true;
801 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
802 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
803 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
804 $message = $this->msg( $this->mParams
['options-message'] )->inContentLanguage()->plain();
807 $this->mOptions
= array();
808 foreach ( explode( "\n", $message ) as $option ) {
809 $value = trim( $option );
810 if ( $value == '' ) {
812 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
813 # A new group is starting...
814 $value = trim( substr( $value, 1 ) );
816 } elseif ( substr( $value, 0, 2 ) == '**' ) {
818 $opt = trim( substr( $value, 2 ) );
819 if ( $optgroup === false ) {
820 $this->mOptions
[$opt] = $opt;
822 $this->mOptions
[$optgroup][$opt] = $opt;
825 # groupless reason list
827 $this->mOptions
[$option] = $option;
831 $this->mOptions
= null;
835 return $this->mOptions
;
839 * flatten an array of options to a single array, for instance,
840 * a set of "<options>" inside "<optgroups>".
842 * @param array $options Associative Array with values either Strings or Arrays
843 * @return array Flattened input
845 public static function flattenOptions( $options ) {
848 foreach ( $options as $value ) {
849 if ( is_array( $value ) ) {
850 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
852 $flatOpts[] = $value;
860 * Formats one or more errors as accepted by field validation-callback.
862 * @param string|Message|array $errors Array of strings or Message instances
863 * @return string HTML
866 protected static function formatErrors( $errors ) {
867 if ( is_array( $errors ) && count( $errors ) === 1 ) {
868 $errors = array_shift( $errors );
871 if ( is_array( $errors ) ) {
873 foreach ( $errors as $error ) {
874 if ( $error instanceof Message
) {
875 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
877 $lines[] = Html
::rawElement( 'li', array(), $error );
881 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
883 if ( $errors instanceof Message
) {
884 $errors = $errors->parse();
887 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );