Merge "Vector: Update comments in vector.js"
[mediawiki.git] / includes / htmlform / HTMLFormField.php
blob0e1860bef057b939309a457a0384cf26e26e373e
1 <?php
3 /**
4 * The parent class to generate form fields. Any field type should
5 * be a subclass of this.
6 */
7 abstract class HTMLFormField {
8 public $mParams;
10 protected $mValidationCallback;
11 protected $mFilterCallback;
12 protected $mName;
13 protected $mLabel; # String label. Set on construction
14 protected $mID;
15 protected $mClass = '';
16 protected $mDefault;
17 protected $mOptions = false;
18 protected $mOptionsLabelsNotFromMessage = false;
19 protected $mHideIf = null;
21 /**
22 * @var bool If true will generate an empty div element with no label
23 * @since 1.22
25 protected $mShowEmptyLabels = true;
27 /**
28 * @var HTMLForm
30 public $mParent;
32 /**
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 );
44 /**
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().
52 * @return Message
54 function msg() {
55 $args = func_get_args();
57 if ( $this->mParent ) {
58 $callback = array( $this->mParent, 'msg' );
59 } else {
60 $callback = 'wfMessage';
63 return call_user_func_array( $callback, $args );
67 /**
68 * Fetch a field value from $alldata for the closest field matching a given
69 * name.
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
77 * @param string $name
78 * @return string
80 protected function getNearestFieldByName( $alldata, $name ) {
81 $tmp = $this->mName;
82 $thisKeys = array();
83 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
84 array_unshift( $thisKeys, $m[2] );
85 $tmp = $m[1];
87 if ( substr( $tmp, 0, 2 ) == 'wp' &&
88 !isset( $alldata[$tmp] ) &&
89 isset( $alldata[substr( $tmp, 2 )] )
90 ) {
91 // Adjust for name mangling.
92 $tmp = substr( $tmp, 2 );
94 array_unshift( $thisKeys, $tmp );
96 $tmp = $name;
97 $nameKeys = array();
98 while ( preg_match( '/^(.+)\[([^\]]+)\]$/', $tmp, $m ) ) {
99 array_unshift( $nameKeys, $m[2] );
100 $tmp = $m[1];
102 array_unshift( $nameKeys, $tmp );
104 $testValue = '';
105 for ( $i = count( $thisKeys ) - 1; $i >= 0; $i-- ) {
106 $keys = array_merge( array_slice( $thisKeys, 0, $i ), $nameKeys );
107 $data = $alldata;
108 while ( $keys ) {
109 $key = array_shift( $keys );
110 if ( !is_array( $data ) || !isset( $data[$key] ) ) {
111 continue 2;
113 $data = $data[$key];
115 $testValue = $data;
116 break;
119 return $testValue;
123 * Helper function for isHidden to handle recursive data structures.
125 * @param array $alldata
126 * @param array $params
127 * @return boolean
129 protected function isHiddenRecurse( array $alldata, array $params ) {
130 $origParams = $params;
131 $op = array_shift( $params );
133 try {
134 switch ( $op ) {
135 case 'AND':
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 ) ) {
143 return false;
146 return true;
148 case 'OR':
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 ) ) {
156 return true;
159 return false;
161 case 'NAND':
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 ) ) {
169 return true;
172 return false;
174 case 'NOR':
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 ) ) {
182 return false;
185 return true;
187 case 'NOT':
188 if ( count( $params ) !== 1 ) {
189 throw new MWException( "NOT takes exactly one parameter" );
191 $p = $params[0];
192 if ( !is_array( $p ) ) {
193 throw new MWException(
194 "Expected array, found " . gettype( $p ) . " at index 0"
197 return !$this->isHiddenRecurse( $alldata, $p );
199 case '===':
200 case '!==':
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 );
209 switch ( $op ) {
210 case '===':
211 return ( $value === $testValue );
212 case '!==':
213 return ( $value !== $testValue );
216 default:
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 ),
223 0, $ex
229 * Test whether this field is supposed to be hidden, based on the values of
230 * the other form fields.
232 * @since 1.23
233 * @param array $alldata The data collected from the form
234 * @return bool
236 function isHidden( $alldata ) {
237 if ( !$this->mHideIf ) {
238 return false;
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.
248 * @since 1.23
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 ) {
255 return false;
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 ) ) {
271 return true;
274 if ( isset( $this->mParams['required'] )
275 && $this->mParams['required'] !== false
276 && $value === ''
278 return $this->msg( 'htmlform-required' )->parse();
281 if ( isset( $this->mValidationCallback ) ) {
282 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
285 return true;
288 function filter( $value, $alldata ) {
289 if ( isset( $this->mFilterCallback ) ) {
290 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
293 return $value;
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() {
303 return true;
307 * Tell the field whether to generate a separate label element if its label
308 * is blank.
310 * @since 1.22
312 * @param bool $show Set to false to not generate a label.
313 * @return void
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 );
329 } else {
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 );
351 } else {
352 $msg = $msgInfo;
353 $msgInfo = array();
356 $this->mLabel = wfMessage( $msg, $msgInfo )->parse();
357 } elseif ( isset( $params['label'] ) ) {
358 if ( $params['label'] === '&#160;' ) {
359 // Apparently some things set &nbsp directly and in an odd format
360 $this->mLabel = '&#160;';
361 } else {
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'] ) ) {
386 $id = $params['id'];
387 $validId = Sanitizer::escapeId( $id );
389 if ( $id != $validId ) {
390 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
393 $this->mID = $id;
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();
436 $rowClasses = '';
438 if ( !empty( $this->mParams['vertical-label'] ) ) {
439 $cellAttributes['colspan'] = 2;
440 $verticalLabel = true;
441 } else {
442 $verticalLabel = false;
445 $label = $this->getLabelHtml( $cellAttributes );
447 $field = Html::rawElement(
448 'td',
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"
465 $field );
466 } else {
467 $html =
468 Html::rawElement( 'tr',
469 $rowAttributes + array(
470 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass $rowClasses"
472 $label . $field );
475 return $html . $helptext;
479 * Get the complete div for the input, including help text,
480 * labels, and whatever.
481 * @since 1.20
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(
496 'mw-input',
497 'mw-htmlform-nolabel' => ( $label === '' )
500 $field = Html::rawElement(
501 'div',
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 );
518 $html .= $helptext;
520 return $html;
524 * Get the complete raw fields for the input, including help text,
525 * labels, and whatever.
526 * @since 1.20
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 );
539 $html = "\n$errors";
540 $html .= $label;
541 $html .= $inputHtml;
542 $html .= $helptext;
544 return $html;
548 * Generate help text HTML in table format
549 * @since 1.20
551 * @param string|null $helptext
552 * @return string
554 public function getHelpTextHtmlTable( $helptext ) {
555 if ( is_null( $helptext ) ) {
556 return '';
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 );
568 return $row;
572 * Generate help text HTML in div format
573 * @since 1.20
575 * @param string|null $helptext
577 * @return string
579 public function getHelpTextHtmlDiv( $helptext ) {
580 if ( is_null( $helptext ) ) {
581 return '';
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 );
593 return $div;
597 * Generate help text HTML formatted for raw output
598 * @since 1.20
600 * @param string|null $helptext
601 * @return string
603 public function getHelpTextHtmlRaw( $helptext ) {
604 return $this->getHelpTextHtmlDiv( $helptext );
608 * Determine the help text to display
609 * @since 1.20
610 * @return string
612 public function getHelpText() {
613 $helptext = null;
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 ) ) {
626 $helptext = '';
627 } else {
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'];
637 return $helptext;
641 * Determine form errors to display and their classes
642 * @since 1.20
644 * @param string $value The value of the input
645 * @return array
647 public function getErrorsAndErrorClass( $value ) {
648 $errors = $this->validate( $value, $this->mParent->mFieldData );
650 if ( is_bool( $errors ) || !$this->mParent->wasSubmitted() ) {
651 $errors = '';
652 $errorClass = '';
653 } else {
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.
668 $for = array();
670 if ( $this->needsLabel() ) {
671 $for['for'] = $this->mID;
674 $labelValue = trim( $this->getLabel() );
675 $hasLabel = false;
676 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
677 $hasLabel = true;
680 $displayFormat = $this->mParent->getDisplayFormat();
681 $html = '';
683 if ( $displayFormat === 'table' ) {
684 $html =
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' ) {
690 $html =
691 Html::rawElement( 'div',
692 array( 'class' => 'mw-label' ) + $cellAttributes,
693 Html::rawElement( 'label', $for, $labelValue ) );
694 } else {
695 $html = Html::rawElement( 'label', $for, $labelValue );
699 return $html;
702 function getDefault() {
703 if ( isset( $this->mDefault ) ) {
704 return $this->mDefault;
705 } else {
706 return null;
711 * Returns the attributes required for the tooltip and accesskey.
713 * @return array Attributes
715 public function getTooltipAndAccessKey() {
716 if ( empty( $this->mParams['tooltip'] ) ) {
717 return array();
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' );
732 $ret = array();
734 foreach ( $list as $key ) {
735 if ( in_array( $key, $boolAttribs ) ) {
736 if ( !empty( $this->mParams[$key] ) ) {
737 $ret[$key] = '';
739 } elseif ( isset( $this->mParams[$key] ) ) {
740 $ret[$key] = $this->mParams[$key];
744 return $ret;
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
752 * @return array
754 private function lookupOptionsKeys( $options ) {
755 $ret = array();
756 foreach ( $options as $key => $value ) {
757 $key = $this->msg( $key )->plain();
758 $ret[$key] = is_array( $value )
759 ? $this->lookupOptionsKeys( $value )
760 : strval( $value );
762 return $ret;
766 * Recursively forces values in an array to strings, because issues arise
767 * with integer 0 as a value.
769 * @param array $array
770 * @return array
772 static function forceToStringRecursive( $array ) {
773 if ( is_array( $array ) ) {
774 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
775 } else {
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();
797 $optgroup = false;
798 $this->mOptions = array();
799 foreach ( explode( "\n", $message ) as $option ) {
800 $value = trim( $option );
801 if ( $value == '' ) {
802 continue;
803 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
804 # A new group is starting...
805 $value = trim( substr( $value, 1 ) );
806 $optgroup = $value;
807 } elseif ( substr( $value, 0, 2 ) == '**' ) {
808 # groupmember
809 $opt = trim( substr( $value, 2 ) );
810 if ( $optgroup === false ) {
811 $this->mOptions[$opt] = $opt;
812 } else {
813 $this->mOptions[$optgroup][$opt] = $opt;
815 } else {
816 # groupless reason list
817 $optgroup = false;
818 $this->mOptions[$option] = $option;
821 } else {
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 ) {
837 $flatOpts = array();
839 foreach ( $options as $value ) {
840 if ( is_array( $value ) ) {
841 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
842 } else {
843 $flatOpts[] = $value;
847 return $flatOpts;
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
855 * @since 1.18
857 protected static function formatErrors( $errors ) {
858 if ( is_array( $errors ) && count( $errors ) === 1 ) {
859 $errors = array_shift( $errors );
862 if ( is_array( $errors ) ) {
863 $lines = array();
864 foreach ( $errors as $error ) {
865 if ( $error instanceof Message ) {
866 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
867 } else {
868 $lines[] = Html::rawElement( 'li', array(), $error );
872 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
873 } else {
874 if ( $errors instanceof Message ) {
875 $errors = $errors->parse();
878 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );