Fix typo reported at twn
[mediawiki.git] / includes / HTMLForm.php
blob35fb020ffe87b9beeb064b14eb7e632f97eb0d27
1 <?php
3 class HTMLForm {
4 static $jsAdded = false;
6 /* The descriptor is an array of arrays.
7 i.e. array(
8 'fieldname' => array( 'section' => 'section/subsection',
9 properties... ),
10 ...
14 static $typeMappings = array(
15 'text' => 'HTMLTextField',
16 'select' => 'HTMLSelectField',
17 'radio' => 'HTMLRadioField',
18 'multiselect' => 'HTMLMultiSelectField',
19 'check' => 'HTMLCheckField',
20 'toggle' => 'HTMLCheckField',
21 'int' => 'HTMLIntField',
22 'float' => 'HTMLFloatField',
23 'info' => 'HTMLInfoField',
24 'selectorother' => 'HTMLSelectOrOtherField',
25 # HTMLTextField will output the correct type="" attribute automagically.
26 # There are about four zillion other HTML 5 input types, like url, but
27 # we don't use those at the moment, so no point in adding all of them.
28 'email' => 'HTMLTextField',
31 function __construct( $descriptor, $messagePrefix ) {
32 $this->mMessagePrefix = $messagePrefix;
34 // Expand out into a tree.
35 $loadedDescriptor = array();
36 $this->mFlatFields = array();
38 foreach( $descriptor as $fieldname => $info ) {
39 $section = '';
40 if ( isset( $info['section'] ) )
41 $section = $info['section'];
43 $info['name'] = $fieldname;
45 $field = $this->loadInputFromParameters( $info );
46 $field->mParent = $this;
48 $setSection =& $loadedDescriptor;
49 if( $section ) {
50 $sectionParts = explode( '/', $section );
52 while( count( $sectionParts ) ) {
53 $newName = array_shift( $sectionParts );
55 if ( !isset( $setSection[$newName] ) ) {
56 $setSection[$newName] = array();
59 $setSection =& $setSection[$newName];
63 $setSection[$fieldname] = $field;
64 $this->mFlatFields[$fieldname] = $field;
67 $this->mFieldTree = $loadedDescriptor;
69 $this->mShowReset = true;
72 static function addJS() {
73 if( self::$jsAdded ) return;
75 global $wgOut;
77 $wgOut->addScriptClass( 'htmlform' );
80 static function loadInputFromParameters( $descriptor ) {
81 if ( isset( $descriptor['class'] ) ) {
82 $class = $descriptor['class'];
83 } elseif ( isset( $descriptor['type'] ) ) {
84 $class = self::$typeMappings[$descriptor['type']];
85 $descriptor['class'] = $class;
88 if( !$class ) {
89 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
92 $obj = new $class( $descriptor );
94 return $obj;
97 function show() {
98 $html = '';
100 self::addJS();
102 // Load data from the request.
103 $this->loadData();
105 // Try a submission
106 global $wgUser, $wgRequest;
107 $editToken = $wgRequest->getVal( 'wpEditToken' );
109 $result = false;
110 if ( $wgUser->matchEditToken( $editToken ) )
111 $result = $this->trySubmit();
113 if( $result === true )
114 return $result;
116 // Display form.
117 $this->displayForm( $result );
120 /** Return values:
121 * TRUE == Successful submission
122 * FALSE == No submission attempted
123 * Anything else == Error to display.
125 function trySubmit() {
126 // Check for validation
127 foreach( $this->mFlatFields as $fieldname => $field ) {
128 if ( !empty( $field->mParams['nodata'] ) ) continue;
129 if ( $field->validate( $this->mFieldData[$fieldname],
130 $this->mFieldData ) !== true ) {
131 return isset( $this->mValidationErrorMessage ) ?
132 $this->mValidationErrorMessage : array( 'htmlform-invalid-input' );
136 $callback = $this->mSubmitCallback;
138 $data = $this->filterDataForSubmit( $this->mFieldData );
140 $res = call_user_func( $callback, $data );
142 return $res;
145 function setSubmitCallback( $cb ) {
146 $this->mSubmitCallback = $cb;
149 function setValidationErrorMessage( $msg ) {
150 $this->mValidationErrorMessage = $msg;
153 function setIntro( $msg ) {
154 $this->mIntro = $msg;
157 function displayForm( $submitResult ) {
158 global $wgOut;
160 if ( $submitResult !== false ) {
161 $this->displayErrors( $submitResult );
164 if ( isset( $this->mIntro ) ) {
165 $wgOut->addHTML( $this->mIntro );
168 $html = $this->getBody();
170 // Hidden fields
171 $html .= $this->getHiddenFields();
173 // Buttons
174 $html .= $this->getButtons();
176 $html = $this->wrapForm( $html );
178 $wgOut->addHTML( $html );
181 function wrapForm( $html ) {
182 return Xml::tags(
183 'form',
184 array(
185 'action' => $this->getTitle()->getFullURL(),
186 'method' => 'post',
188 $html
192 function getHiddenFields() {
193 global $wgUser;
194 $html = '';
196 $html .= Xml::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
197 $html .= Xml::hidden( 'title', $this->getTitle() ) . "\n";
199 return $html;
202 function getButtons() {
203 $html = '';
205 $attribs = array();
207 if ( isset( $this->mSubmitID ) )
208 $attribs['id'] = $this->mSubmitID;
210 $attribs['class'] = 'mw-htmlform-submit';
212 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
214 if( $this->mShowReset ) {
215 $html .= Xml::element(
216 'input',
217 array(
218 'type' => 'reset',
219 'value' => wfMsg( 'htmlform-reset' )
221 ) . "\n";
224 return $html;
227 function getBody() {
228 return $this->displaySection( $this->mFieldTree );
231 function displayErrors( $errors ) {
232 if ( is_array( $errors ) ) {
233 $errorstr = $this->formatErrors( $errors );
234 } else {
235 $errorstr = $errors;
238 $errorstr = Xml::tags( 'div', array( 'class' => 'error' ), $errorstr );
240 global $wgOut;
241 $wgOut->addHTML( $errorstr );
244 static function formatErrors( $errors ) {
245 $errorstr = '';
246 foreach ( $errors as $error ) {
247 if( is_array( $error ) ) {
248 $msg = array_shift( $error );
249 } else {
250 $msg = $error;
251 $error = array();
253 $errorstr .= Xml::tags(
254 'li',
255 null,
256 wfMsgExt( $msg, array( 'parseinline' ), $error )
260 $errorstr = Xml::tags( 'ul', null, $errorstr );
262 return $errorstr;
265 function setSubmitText( $t ) {
266 $this->mSubmitText = $t;
269 function getSubmitText() {
270 return isset( $this->mSubmitText ) ? $this->mSubmitText : wfMsg( 'htmlform-submit' );
273 function setSubmitID( $t ) {
274 $this->mSubmitID = $t;
277 function setMessagePrefix( $p ) {
278 $this->mMessagePrefix = $p;
281 function setTitle( $t ) {
282 $this->mTitle = $t;
285 function getTitle() {
286 return $this->mTitle;
289 function displaySection( $fields ) {
290 $tableHtml = '';
291 $subsectionHtml = '';
292 $hasLeftColumn = false;
294 foreach( $fields as $key => $value ) {
295 if ( is_object( $value ) ) {
296 $v = empty( $value->mParams['nodata'] )
297 ? $this->mFieldData[$key]
298 : $value->getDefault();
299 $tableHtml .= $value->getTableRow( $v );
301 if( $value->getLabel() != '&nbsp;' )
302 $hasLeftColumn = true;
303 } elseif ( is_array( $value ) ) {
304 $section = $this->displaySection( $value );
305 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
306 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
310 $classes = array();
311 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
312 $classes[] = 'mw-htmlform-nolabel';
313 $classes = implode( ' ', $classes );
315 $tableHtml = "<table class='$classes'><tbody>\n$tableHtml\n</tbody></table>\n";
317 return $subsectionHtml . "\n" . $tableHtml;
320 function loadData() {
321 global $wgRequest;
323 $fieldData = array();
325 foreach( $this->mFlatFields as $fieldname => $field ) {
326 if ( !empty( $field->mParams['nodata'] ) ) continue;
327 if ( !empty( $field->mParams['disabled'] ) ) {
328 $fieldData[$fieldname] = $field->getDefault();
329 } else {
330 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
334 // Filter data.
335 foreach( $fieldData as $name => &$value ) {
336 $field = $this->mFlatFields[$name];
337 $value = $field->filter( $value, $this->mFlatFields );
340 $this->mFieldData = $fieldData;
343 function importData( $fieldData ) {
344 // Filter data.
345 foreach( $fieldData as $name => &$value ) {
346 $field = $this->mFlatFields[$name];
347 $value = $field->filter( $value, $this->mFlatFields );
350 foreach( $this->mFlatFields as $fieldname => $field ) {
351 if ( !isset( $fieldData[$fieldname] ) )
352 $fieldData[$fieldname] = $field->getDefault();
355 $this->mFieldData = $fieldData;
358 function suppressReset( $suppressReset = true ) {
359 $this->mShowReset = !$suppressReset;
362 function filterDataForSubmit( $data ) {
363 return $data;
367 abstract class HTMLFormField {
368 abstract function getInputHTML( $value );
370 function validate( $value, $alldata ) {
371 if ( isset( $this->mValidationCallback ) ) {
372 return call_user_func( $this->mValidationCallback, $value, $alldata );
375 return true;
378 function filter( $value, $alldata ) {
379 if( isset( $this->mFilterCallback ) ) {
380 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
383 return $value;
386 function loadDataFromRequest( $request ) {
387 if( $request->getCheck( $this->mName ) ) {
388 return $request->getText( $this->mName );
389 } else {
390 return $this->getDefault();
394 function __construct( $params ) {
395 $this->mParams = $params;
397 if( isset( $params['label-message'] ) ) {
398 $msgInfo = $params['label-message'];
400 if ( is_array( $msgInfo ) ) {
401 $msg = array_shift( $msgInfo );
402 } else {
403 $msg = $msgInfo;
404 $msgInfo = array();
407 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
408 } elseif ( isset( $params['label'] ) ) {
409 $this->mLabel = $params['label'];
412 if ( isset( $params['name'] ) ) {
413 $name = $params['name'];
414 $validName = Sanitizer::escapeId( $name );
415 if( $name != $validName ) {
416 throw new MWException("Invalid name '$name' passed to " . __METHOD__ );
418 $this->mName = 'wp'.$name;
419 $this->mID = 'mw-input-'.$name;
422 if ( isset( $params['default'] ) ) {
423 $this->mDefault = $params['default'];
426 if ( isset( $params['id'] ) ) {
427 $id = $params['id'];
428 $validId = Sanitizer::escapeId( $id );
429 if( $id != $validId ) {
430 throw new MWException("Invalid id '$id' passed to " . __METHOD__ );
432 $this->mID = $id;
435 if ( isset( $params['validation-callback'] ) ) {
436 $this->mValidationCallback = $params['validation-callback'];
439 if ( isset( $params['filter-callback'] ) ) {
440 $this->mFilterCallback = $params['filter-callback'];
444 function getTableRow( $value ) {
445 // Check for invalid data.
446 global $wgRequest;
448 $errors = $this->validate( $value, $this->mParent->mFieldData );
449 if ( $errors === true || !$wgRequest->wasPosted() ) {
450 $errors = '';
451 } else {
452 $errors = Xml::tags( 'span', array( 'class' => 'error' ), $errors );
455 $html = '';
457 $html .= Xml::tags( 'td', array( 'class' => 'mw-label' ),
458 Xml::tags( 'label', array( 'for' => $this->mID ), $this->getLabel() )
460 $html .= Xml::tags( 'td', array( 'class' => 'mw-input' ),
461 $this->getInputHTML( $value ) ."\n$errors" );
463 $fieldType = get_class( $this );
465 $html = Xml::tags( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
466 $html ) . "\n";
468 $helptext = null;
469 if ( isset( $this->mParams['help-message'] ) ) {
470 $msg = $this->mParams['help-message'];
471 $helptext = wfMsgExt( $msg, 'parseinline' );
472 if ( wfEmptyMsg( $msg, $helptext ) ) {
473 # Never mind
474 $helptext = null;
476 } elseif ( isset( $this->mParams['help'] ) ) {
477 $helptext = $this->mParams['help'];
480 if ( !is_null( $helptext ) ) {
481 $row = Xml::tags( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
482 $helptext );
483 $row = Xml::tags( 'tr', null, $row );
484 $html .= "$row\n";
487 return $html;
490 function getLabel() {
491 return $this->mLabel;
494 function getDefault() {
495 if ( isset( $this->mDefault ) ) {
496 return $this->mDefault;
497 } else {
498 return null;
502 static function flattenOptions( $options ) {
503 $flatOpts = array();
505 foreach( $options as $key => $value ) {
506 if ( is_array( $value ) ) {
507 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
508 } else {
509 $flatOpts[] = $value;
513 return $flatOpts;
517 class HTMLTextField extends HTMLFormField {
518 function getSize() {
519 return isset( $this->mParams['size'] ) ? $this->mParams['size'] : 45;
522 function getInputHTML( $value ) {
523 global $wgHtml5;
524 $attribs = array( 'id' => $this->mID );
526 if ( isset( $this->mParams['maxlength'] ) ) {
527 $attribs['maxlength'] = $this->mParams['maxlength'];
530 if ( !empty( $this->mParams['disabled'] ) ) {
531 $attribs['disabled'] = 'disabled';
534 if ( $wgHtml5 ) {
535 # TODO: Enforce pattern, step, required, readonly on the server
536 # side as well
537 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
538 'placeholder' ) as $param ) {
539 if ( isset( $this->mParams[$param] ) ) {
540 $attribs[$param] = $this->mParams[$param];
543 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' )
544 as $param ) {
545 if ( isset( $this->mParams[$param] ) ) {
546 $attribs[$param] = '';
549 if ( isset( $this->mParams['type'] ) ) {
550 switch ( $this->mParams['type'] ) {
551 case 'email':
552 $attribs['type'] = 'email';
553 break;
554 case 'int':
555 $attribs['type'] = 'number';
556 break;
557 case 'float':
558 $attribs['type'] = 'number';
559 $attribs['step'] = 'any';
560 break;
565 return Xml::input(
566 $this->mName,
567 $this->getSize(),
568 $value,
569 $attribs
574 class HTMLFloatField extends HTMLTextField {
575 function getSize() {
576 return isset( $this->mParams['size'] ) ? $this->mParams['size'] : 20;
579 function validate( $value, $alldata ) {
580 $p = parent::validate( $value, $alldata );
582 if ( $p !== true ) return $p;
584 if ( floatval( $value ) != $value ) {
585 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
588 $in_range = true;
590 # The "int" part of these message names is rather confusing. They make
591 # equal sense for all numbers.
592 if ( isset( $this->mParams['min'] ) ) {
593 $min = $this->mParams['min'];
594 if ( $min > $value )
595 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
598 if ( isset( $this->mParams['max'] ) ) {
599 $max = $this->mParams['max'];
600 if( $max < $value )
601 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
604 return true;
608 class HTMLIntField extends HTMLFloatField {
609 function validate( $value, $alldata ) {
610 $p = parent::validate( $value, $alldata );
612 if ( $p !== true ) return $p;
614 if ( intval( $value ) != $value ) {
615 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
618 return true;
622 class HTMLCheckField extends HTMLFormField {
623 function getInputHTML( $value ) {
624 if ( !empty( $this->mParams['invert'] ) )
625 $value = !$value;
627 $attr = array( 'id' => $this->mID );
628 if( !empty( $this->mParams['disabled'] ) ) {
629 $attr['disabled'] = 'disabled';
632 return Xml::check( $this->mName, $value, $attr ) . '&nbsp;' .
633 Xml::tags( 'label', array( 'for' => $this->mID ), $this->mLabel );
636 function getLabel() {
637 return '&nbsp;'; // In the right-hand column.
640 function loadDataFromRequest( $request ) {
641 $invert = false;
642 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
643 $invert = true;
646 // GetCheck won't work like we want for checks.
647 if( $request->getCheck( 'wpEditToken' ) ) {
648 // XOR has the following truth table, which is what we want
649 // INVERT VALUE | OUTPUT
650 // true true | false
651 // false true | true
652 // false false | false
653 // true false | true
654 return $request->getBool( $this->mName ) xor $invert;
655 } else {
656 return $this->getDefault();
661 class HTMLSelectField extends HTMLFormField {
663 function validate( $value, $alldata ) {
664 $p = parent::validate( $value, $alldata );
665 if( $p !== true ) return $p;
667 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
668 if ( in_array( $value, $validOptions ) )
669 return true;
670 else
671 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
674 function getInputHTML( $value ) {
675 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
677 // If one of the options' 'name' is int(0), it is automatically selected.
678 // because PHP sucks and things int(0) == 'some string'.
679 // Working around this by forcing all of them to strings.
680 $options = array_map( 'strval', $this->mParams['options'] );
682 if( !empty( $this->mParams['disabled'] ) ) {
683 $select->setAttribute( 'disabled', 'disabled' );
686 $select->addOptions( $options );
688 return $select->getHTML();
692 class HTMLSelectOrOtherField extends HTMLTextField {
693 static $jsAdded = false;
695 function __construct( $params ) {
696 if( !in_array( 'other', $params['options'] ) ) {
697 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
700 parent::__construct( $params );
703 static function forceToStringRecursive( $array ) {
704 if ( is_array($array) ) {
705 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array);
706 } else {
707 return strval($array);
711 function getInputHTML( $value ) {
712 $valInSelect = false;
714 if( $value !== false )
715 $valInSelect = in_array( $value,
716 HTMLFormField::flattenOptions( $this->mParams['options'] ) );
718 $selected = $valInSelect ? $value : 'other';
720 $opts = self::forceToStringRecursive( $this->mParams['options'] );
722 $select = new XmlSelect( $this->mName, $this->mID, $selected );
723 $select->addOptions( $opts );
725 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
727 $tbAttribs = array( 'id' => $this->mID . '-other' );
728 if( !empty( $this->mParams['disabled'] ) ) {
729 $select->setAttribute( 'disabled', 'disabled' );
730 $tbAttribs['disabled'] = 'disabled';
733 $select = $select->getHTML();
735 if ( isset( $this->mParams['maxlength'] ) ) {
736 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
739 $textbox = Xml::input( $this->mName . '-other',
740 $this->getSize(),
741 $valInSelect ? '' : $value,
742 $tbAttribs );
744 return "$select<br/>\n$textbox";
747 function loadDataFromRequest( $request ) {
748 if( $request->getCheck( $this->mName ) ) {
749 $val = $request->getText( $this->mName );
751 if( $val == 'other' ) {
752 $val = $request->getText( $this->mName . '-other' );
755 return $val;
756 } else {
757 return $this->getDefault();
762 class HTMLMultiSelectField extends HTMLFormField {
763 function validate( $value, $alldata ) {
764 $p = parent::validate( $value, $alldata );
765 if( $p !== true ) return $p;
767 if( !is_array( $value ) ) return false;
769 // If all options are valid, array_intersect of the valid options and the provided
770 // options will return the provided options.
771 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
773 $validValues = array_intersect( $value, $validOptions );
774 if ( count( $validValues ) == count( $value ) )
775 return true;
776 else
777 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
780 function getInputHTML( $value ) {
781 $html = $this->formatOptions( $this->mParams['options'], $value );
783 return $html;
786 function formatOptions( $options, $value ) {
787 $html = '';
789 $attribs = array();
790 if ( !empty( $this->mParams['disabled'] ) ) {
791 $attribs['disabled'] = 'disabled';
794 foreach( $options as $label => $info ) {
795 if( is_array( $info ) ) {
796 $html .= Xml::tags( 'h1', null, $label ) . "\n";
797 $html .= $this->formatOptions( $info, $value );
798 } else {
799 $thisAttribs = array( 'id' => $this->mID . "-$info", 'value' => $info );
801 $checkbox = Xml::check( $this->mName . '[]', in_array( $info, $value ),
802 $attribs + $thisAttribs );
803 $checkbox .= '&nbsp;' . Xml::tags( 'label', array( 'for' => $this->mID . "-$info" ), $label );
805 $html .= $checkbox . '<br />';
809 return $html;
812 function loadDataFromRequest( $request ) {
813 // won't work with getCheck
814 if( $request->getCheck( 'wpEditToken' ) ) {
815 $arr = $request->getArray( $this->mName );
817 if( !$arr )
818 $arr = array();
820 return $arr;
821 } else {
822 return $this->getDefault();
826 function getDefault() {
827 if ( isset( $this->mDefault ) ) {
828 return $this->mDefault;
829 } else {
830 return array();
835 class HTMLRadioField extends HTMLFormField {
836 function validate( $value, $alldata ) {
837 $p = parent::validate( $value, $alldata );
838 if( $p !== true ) return $p;
840 if( !is_string( $value ) && !is_int( $value ) )
841 return false;
843 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
845 if ( in_array( $value, $validOptions ) )
846 return true;
847 else
848 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
851 function getInputHTML( $value ) {
852 $html = $this->formatOptions( $this->mParams['options'], $value );
854 return $html;
857 function formatOptions( $options, $value ) {
858 $html = '';
860 $attribs = array();
861 if ( !empty( $this->mParams['disabled'] ) ) {
862 $attribs['disabled'] = 'disabled';
865 foreach( $options as $label => $info ) {
866 if( is_array( $info ) ) {
867 $html .= Xml::tags( 'h1', null, $label ) . "\n";
868 $html .= $this->formatOptions( $info, $value );
869 } else {
870 $id = Sanitizer::escapeId( $this->mID . "-$info" );
871 $html .= Xml::radio( $this->mName, $info, $info == $value,
872 $attribs + array( 'id' => $id ) );
873 $html .= '&nbsp;' .
874 Xml::tags( 'label', array( 'for' => $id ), $label );
876 $html .= "<br/>\n";
880 return $html;
884 class HTMLInfoField extends HTMLFormField {
885 function __construct( $info ) {
886 $info['nodata'] = true;
888 parent::__construct( $info );
891 function getInputHTML( $value ) {
892 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
895 function getTableRow( $value ) {
896 if ( !empty( $this->mParams['rawrow'] ) ) {
897 return $value;
900 return parent::getTableRow( $value );