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 = '';
17 protected $mOptions = false;
18 protected $mOptionsLabelsNotFromMessage = false;
19 protected $mHideIf = null;
22 * @var bool If true will generate an empty div element with no label
25 protected $mShowEmptyLabels = true;
33 * This function must be implemented to return the HTML to generate
34 * the input object itself. It should not implement the surrounding
35 * table cells/rows, or labels/help messages.
37 * @param string $value the value to set the input to; eg a default
38 * text for a text input.
40 * @return string Valid HTML.
42 abstract function getInputHTML( $value );
45 * Get a translated interface message
47 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
48 * and wfMessage() otherwise.
50 * Parameters are the same as wfMessage().
55 $args = func_get_args();
57 if ( $this->mParent
) {
58 $callback = array( $this->mParent
, 'msg' );
60 $callback = 'wfMessage';
63 return call_user_func_array( $callback, $args );
68 * Fetch a field value from $alldata for the closest field matching a given
71 * This is complex because it needs to handle array fields like the user
72 * would expect. The general algorithm is to look for $name as a sibling
73 * of $this, then a sibling of $this's parent, and so on. Keeping in mind
74 * that $name itself might be referencing an array.
76 * @param array $alldata
80 protected function getNearestFieldByName( $alldata, $name ) {
83 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
84 array_unshift( $thisKeys, $m[2] );
87 if ( substr( $tmp, 0, 2 ) == 'wp' &&
88 !isset( $alldata[$tmp] ) &&
89 isset( $alldata[substr( $tmp, 2 )] )
91 // Adjust for name mangling.
92 $tmp = substr( $tmp, 2 );
94 array_unshift( $thisKeys, $tmp );
98 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
99 array_unshift( $nameKeys, $m[2] );
102 array_unshift( $nameKeys, $tmp );
105 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
106 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
109 $key = array_shift( $keys );
110 if ( !is_array( $data ) ||
!isset( $data[$key] ) ) {
123 * Helper function for isHidden to handle recursive data structures.
125 * @param array $alldata
126 * @param array $params
129 protected function isHiddenRecurse( array $alldata, array $params ) {
130 $origParams = $params;
131 $op = array_shift( $params );
136 foreach ( $params as $i => $p ) {
137 if ( !is_array( $p ) ) {
138 throw new MWException(
139 "Expected array, found " . gettype( $p ) . " at index $i"
142 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
149 foreach ( $params as $p ) {
150 if ( !is_array( $p ) ) {
151 throw new MWException(
152 "Expected array, found " . gettype( $p ) . " at index $i"
155 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
162 foreach ( $params as $i => $p ) {
163 if ( !is_array( $p ) ) {
164 throw new MWException(
165 "Expected array, found " . gettype( $p ) . " at index $i"
168 if ( !$this->isHiddenRecurse( $alldata, $p ) ) {
175 foreach ( $params as $p ) {
176 if ( !is_array( $p ) ) {
177 throw new MWException(
178 "Expected array, found " . gettype( $p ) . " at index $i"
181 if ( $this->isHiddenRecurse( $alldata, $p ) ) {
188 if ( count( $params ) !== 1 ) {
189 throw new MWException( "NOT takes exactly one parameter" );
192 if ( !is_array( $p ) ) {
193 throw new MWException(
194 "Expected array, found " . gettype( $p ) . " at index 0"
197 return !$this->isHiddenRecurse( $alldata, $p );
201 if ( count( $params ) !== 2 ) {
202 throw new MWException( "$op takes exactly two parameters" );
204 list( $field, $value ) = $params;
205 if ( !is_string( $field ) ||
!is_string( $value ) ) {
206 throw new MWException( "Parameters for $op must be strings" );
208 $testValue = $this->getNearestFieldByName( $alldata, $field );
211 return ( $value === $testValue );
213 return ( $value !== $testValue );
217 throw new MWException( "Unknown operation" );
219 } catch ( MWException
$ex ) {
220 throw new MWException(
221 "Invalid hide-if specification for $this->mName: " .
222 $ex->getMessage() . " in " . var_export( $origParams, true ),
229 * Test whether this field is supposed to be hidden, based on the values of
230 * the other form fields.
233 * @param array $alldata The data collected from the form
236 function isHidden( $alldata ) {
237 if ( !$this->mHideIf
) {
241 return $this->isHiddenRecurse( $alldata, $this->mHideIf
);
245 * Override this function if the control can somehow trigger a form
246 * submission that shouldn't actually submit the HTMLForm.
249 * @param string|array $value The value the field was submitted with
250 * @param array $alldata The data collected from the form
252 * @return bool true to cancel the submission
254 function cancelSubmit( $value, $alldata ) {
259 * Override this function to add specific validation checks on the
260 * field input. Don't forget to call parent::validate() to ensure
261 * that the user-defined callback mValidationCallback is still run
263 * @param string|array $value The value the field was submitted with
264 * @param array $alldata The data collected from the form
266 * @return bool|string true on success, or String error to display, or
267 * false to fail validation without displaying an error.
269 function validate( $value, $alldata ) {
270 if ( $this->isHidden( $alldata ) ) {
274 if ( isset( $this->mParams
['required'] )
275 && $this->mParams
['required'] !== false
278 return $this->msg( 'htmlform-required' )->parse();
281 if ( isset( $this->mValidationCallback
) ) {
282 return call_user_func( $this->mValidationCallback
, $value, $alldata, $this->mParent
);
288 function filter( $value, $alldata ) {
289 if ( isset( $this->mFilterCallback
) ) {
290 $value = call_user_func( $this->mFilterCallback
, $value, $alldata, $this->mParent
);
297 * Should this field have a label, or is there no input element with the
298 * appropriate id for the label to point to?
300 * @return bool True to output a label, false to suppress
302 protected function needsLabel() {
307 * Tell the field whether to generate a separate label element if its label
312 * @param bool $show Set to false to not generate a label.
315 public function setShowEmptyLabel( $show ) {
316 $this->mShowEmptyLabels
= $show;
320 * Get the value that this input has been set to from a posted form,
321 * or the input's default value if it has not been set.
323 * @param WebRequest $request
324 * @return string The value
326 function loadDataFromRequest( $request ) {
327 if ( $request->getCheck( $this->mName
) ) {
328 return $request->getText( $this->mName
);
330 return $this->getDefault();
335 * Initialise the object
337 * @param array $params Associative Array. See HTMLForm doc for syntax.
339 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
340 * @throws MWException
342 function __construct( $params ) {
343 $this->mParams
= $params;
345 # Generate the label from a message, if possible
346 if ( isset( $params['label-message'] ) ) {
347 $msgInfo = $params['label-message'];
349 if ( is_array( $msgInfo ) ) {
350 $msg = array_shift( $msgInfo );
356 $this->mLabel
= wfMessage( $msg, $msgInfo )->parse();
357 } elseif ( isset( $params['label'] ) ) {
358 if ( $params['label'] === ' ' ) {
359 // Apparently some things set   directly and in an odd format
360 $this->mLabel
= ' ';
362 $this->mLabel
= htmlspecialchars( $params['label'] );
364 } elseif ( isset( $params['label-raw'] ) ) {
365 $this->mLabel
= $params['label-raw'];
368 $this->mName
= "wp{$params['fieldname']}";
369 if ( isset( $params['name'] ) ) {
370 $this->mName
= $params['name'];
373 $validName = Sanitizer
::escapeId( $this->mName
);
374 $validName = str_replace( array( '.5B', '.5D' ), array( '[', ']' ), $validName );
375 if ( $this->mName
!= $validName && !isset( $params['nodata'] ) ) {
376 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__
);
379 $this->mID
= "mw-input-{$this->mName}";
381 if ( isset( $params['default'] ) ) {
382 $this->mDefault
= $params['default'];
385 if ( isset( $params['id'] ) ) {
387 $validId = Sanitizer
::escapeId( $id );
389 if ( $id != $validId ) {
390 throw new MWException( "Invalid id '$id' passed to " . __METHOD__
);
396 if ( isset( $params['cssclass'] ) ) {
397 $this->mClass
= $params['cssclass'];
400 if ( isset( $params['validation-callback'] ) ) {
401 $this->mValidationCallback
= $params['validation-callback'];
404 if ( isset( $params['filter-callback'] ) ) {
405 $this->mFilterCallback
= $params['filter-callback'];
408 if ( isset( $params['flatlist'] ) ) {
409 $this->mClass
.= ' mw-htmlform-flatlist';
412 if ( isset( $params['hidelabel'] ) ) {
413 $this->mShowEmptyLabels
= false;
416 if ( isset( $params['hide-if'] ) ) {
417 $this->mHideIf
= $params['hide-if'];
422 * Get the complete table row for the input, including help text,
423 * labels, and whatever.
425 * @param string $value The value to set the input to.
427 * @return string Complete HTML table row.
429 function getTableRow( $value ) {
430 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
431 $inputHtml = $this->getInputHTML( $value );
432 $fieldType = get_class( $this );
433 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
434 $cellAttributes = array();
435 $rowAttributes = array();
438 if ( !empty( $this->mParams
['vertical-label'] ) ) {
439 $cellAttributes['colspan'] = 2;
440 $verticalLabel = true;
442 $verticalLabel = false;
445 $label = $this->getLabelHtml( $cellAttributes );
447 $field = Html
::rawElement(
449 array( 'class' => 'mw-input' ) +
$cellAttributes,
450 $inputHtml . "\n$errors"
453 if ( $this->mHideIf
) {
454 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
455 $rowClasses .= ' mw-htmlform-hide-if';
458 if ( $verticalLabel ) {
459 $html = Html
::rawElement( 'tr',
460 $rowAttributes +
array( 'class' => "mw-htmlform-vertical-label $rowClasses" ), $label );
461 $html .= Html
::rawElement( 'tr',
462 $rowAttributes +
array(
463 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
468 Html
::rawElement( 'tr',
469 $rowAttributes +
array(
470 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
475 return $html . $helptext;
479 * Get the complete div for the input, including help text,
480 * labels, and whatever.
483 * @param string $value The value to set the input to.
485 * @return string Complete HTML table row.
487 public function getDiv( $value ) {
488 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
489 $inputHtml = $this->getInputHTML( $value );
490 $fieldType = get_class( $this );
491 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
492 $cellAttributes = array();
493 $label = $this->getLabelHtml( $cellAttributes );
495 $outerDivClass = array(
497 'mw-htmlform-nolabel' => ( $label === '' )
500 $field = Html
::rawElement(
502 array( 'class' => $outerDivClass ) +
$cellAttributes,
503 $inputHtml . "\n$errors"
505 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass
, $errorClass );
506 if ( $this->mParent
->isVForm() ) {
507 $divCssClasses[] = 'mw-ui-vform-div';
510 $wrapperAttributes = array(
511 'class' => $divCssClasses,
513 if ( $this->mHideIf
) {
514 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
515 $wrapperAttributes['class'][] = ' mw-htmlform-hide-if';
517 $html = Html
::rawElement( 'div', $wrapperAttributes, $label . $field );
524 * Get the complete raw fields for the input, including help text,
525 * labels, and whatever.
528 * @param string $value The value to set the input to.
530 * @return string Complete HTML table row.
532 public function getRaw( $value ) {
533 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
534 $inputHtml = $this->getInputHTML( $value );
535 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
536 $cellAttributes = array();
537 $label = $this->getLabelHtml( $cellAttributes );
548 * Generate help text HTML in table format
551 * @param string|null $helptext
554 public function getHelpTextHtmlTable( $helptext ) {
555 if ( is_null( $helptext ) ) {
559 $rowAttributes = array();
560 if ( $this->mHideIf
) {
561 $rowAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
562 $rowAttributes['class'] = 'mw-htmlform-hide-if';
565 $row = Html
::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ), $helptext );
566 $row = Html
::rawElement( 'tr', $rowAttributes, $row );
572 * Generate help text HTML in div format
575 * @param string|null $helptext
579 public function getHelpTextHtmlDiv( $helptext ) {
580 if ( is_null( $helptext ) ) {
584 $wrapperAttributes = array(
585 'class' => 'htmlform-tip',
587 if ( $this->mHideIf
) {
588 $wrapperAttributes['data-hide-if'] = FormatJson
::encode( $this->mHideIf
);
589 $wrapperAttributes['class'] .= ' mw-htmlform-hide-if';
591 $div = Html
::rawElement( 'div', $wrapperAttributes, $helptext );
597 * Generate help text HTML formatted for raw output
600 * @param string|null $helptext
603 public function getHelpTextHtmlRaw( $helptext ) {
604 return $this->getHelpTextHtmlDiv( $helptext );
608 * Determine the help text to display
612 public function getHelpText() {
615 if ( isset( $this->mParams
['help-message'] ) ) {
616 $this->mParams
['help-messages'] = array( $this->mParams
['help-message'] );
619 if ( isset( $this->mParams
['help-messages'] ) ) {
620 foreach ( $this->mParams
['help-messages'] as $name ) {
621 $helpMessage = (array)$name;
622 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
624 if ( $msg->exists() ) {
625 if ( is_null( $helptext ) ) {
628 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
630 $helptext .= $msg->parse(); // Append message
633 } elseif ( isset( $this->mParams
['help'] ) ) {
634 $helptext = $this->mParams
['help'];
641 * Determine form errors to display and their classes
644 * @param string $value The value of the input
647 public function getErrorsAndErrorClass( $value ) {
648 $errors = $this->validate( $value, $this->mParent
->mFieldData
);
650 if ( is_bool( $errors ) ||
!$this->mParent
->wasSubmitted() ) {
654 $errors = self
::formatErrors( $errors );
655 $errorClass = 'mw-htmlform-invalid-input';
658 return array( $errors, $errorClass );
661 function getLabel() {
662 return is_null( $this->mLabel
) ?
'' : $this->mLabel
;
665 function getLabelHtml( $cellAttributes = array() ) {
666 # Don't output a for= attribute for labels with no associated input.
667 # Kind of hacky here, possibly we don't want these to be <label>s at all.
670 if ( $this->needsLabel() ) {
671 $for['for'] = $this->mID
;
674 $labelValue = trim( $this->getLabel() );
676 if ( $labelValue !== ' ' && $labelValue !== '' ) {
680 $displayFormat = $this->mParent
->getDisplayFormat();
683 if ( $displayFormat === 'table' ) {
685 Html
::rawElement( 'td',
686 array( 'class' => 'mw-label' ) +
$cellAttributes,
687 Html
::rawElement( 'label', $for, $labelValue ) );
688 } elseif ( $hasLabel ||
$this->mShowEmptyLabels
) {
689 if ( $displayFormat === 'div' ) {
691 Html
::rawElement( 'div',
692 array( 'class' => 'mw-label' ) +
$cellAttributes,
693 Html
::rawElement( 'label', $for, $labelValue ) );
695 $html = Html
::rawElement( 'label', $for, $labelValue );
702 function getDefault() {
703 if ( isset( $this->mDefault
) ) {
704 return $this->mDefault
;
711 * Returns the attributes required for the tooltip and accesskey.
713 * @return array Attributes
715 public function getTooltipAndAccessKey() {
716 if ( empty( $this->mParams
['tooltip'] ) ) {
720 return Linker
::tooltipAndAccesskeyAttribs( $this->mParams
['tooltip'] );
724 * Returns the given attributes from the parameters
726 * @param array $list List of attributes to get
727 * @return array Attributes
729 public function getAttributes( array $list ) {
730 static $boolAttribs = array( 'disabled', 'required', 'autofocus', 'multiple', 'readonly' );
734 foreach ( $list as $key ) {
735 if ( in_array( $key, $boolAttribs ) ) {
736 if ( !empty( $this->mParams
[$key] ) ) {
739 } elseif ( isset( $this->mParams
[$key] ) ) {
740 $ret[$key] = $this->mParams
[$key];
748 * Given an array of msg-key => value mappings, returns an array with keys
749 * being the message texts. It also forces values to strings.
751 * @param array $options
754 private function lookupOptionsKeys( $options ) {
756 foreach ( $options as $key => $value ) {
757 $key = $this->msg( $key )->plain();
758 $ret[$key] = is_array( $value )
759 ?
$this->lookupOptionsKeys( $value )
766 * Recursively forces values in an array to strings, because issues arise
767 * with integer 0 as a value.
769 * @param array $array
772 static function forceToStringRecursive( $array ) {
773 if ( is_array( $array ) ) {
774 return array_map( array( __CLASS__
, 'forceToStringRecursive' ), $array );
776 return strval( $array );
781 * Fetch the array of options from the field's parameters. In order, this
782 * checks 'options-messages', 'options', then 'options-message'.
784 * @return array|null Options array
786 public function getOptions() {
787 if ( $this->mOptions
=== false ) {
788 if ( array_key_exists( 'options-messages', $this->mParams
) ) {
789 $this->mOptions
= $this->lookupOptionsKeys( $this->mParams
['options-messages'] );
790 } elseif ( array_key_exists( 'options', $this->mParams
) ) {
791 $this->mOptionsLabelsNotFromMessage
= true;
792 $this->mOptions
= self
::forceToStringRecursive( $this->mParams
['options'] );
793 } elseif ( array_key_exists( 'options-message', $this->mParams
) ) {
794 /** @todo This is copied from Xml::listDropDown(), deprecate/avoid duplication? */
795 $message = $this->msg( $this->mParams
['options-message'] )->inContentLanguage()->plain();
798 $this->mOptions
= array();
799 foreach ( explode( "\n", $message ) as $option ) {
800 $value = trim( $option );
801 if ( $value == '' ) {
803 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
804 # A new group is starting...
805 $value = trim( substr( $value, 1 ) );
807 } elseif ( substr( $value, 0, 2 ) == '**' ) {
809 $opt = trim( substr( $value, 2 ) );
810 if ( $optgroup === false ) {
811 $this->mOptions
[$opt] = $opt;
813 $this->mOptions
[$optgroup][$opt] = $opt;
816 # groupless reason list
818 $this->mOptions
[$option] = $option;
822 $this->mOptions
= null;
826 return $this->mOptions
;
830 * flatten an array of options to a single array, for instance,
831 * a set of "<options>" inside "<optgroups>".
833 * @param array $options Associative Array with values either Strings or Arrays
834 * @return array Flattened input
836 public static function flattenOptions( $options ) {
839 foreach ( $options as $value ) {
840 if ( is_array( $value ) ) {
841 $flatOpts = array_merge( $flatOpts, self
::flattenOptions( $value ) );
843 $flatOpts[] = $value;
851 * Formats one or more errors as accepted by field validation-callback.
853 * @param string|Message|array $errors Array of strings or Message instances
854 * @return string HTML
857 protected static function formatErrors( $errors ) {
858 if ( is_array( $errors ) && count( $errors ) === 1 ) {
859 $errors = array_shift( $errors );
862 if ( is_array( $errors ) ) {
864 foreach ( $errors as $error ) {
865 if ( $error instanceof Message
) {
866 $lines[] = Html
::rawElement( 'li', array(), $error->parse() );
868 $lines[] = Html
::rawElement( 'li', array(), $error );
872 return Html
::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
874 if ( $errors instanceof Message
) {
875 $errors = $errors->parse();
878 return Html
::rawElement( 'span', array( 'class' => 'error' ), $errors );