Localisation updates for core messages from translatewiki.net (2009-05-02 21:29 UTC)
[mediawiki.git] / includes / HTMLForm.php
blobc06bd9e6ed3c323ab2c722fbccdc8a29e3b958d2
1 <?php
3 class HTMLForm {
5 static $jsAdded = false;
7 /* The descriptor is an array of arrays.
8 i.e. array(
9 'fieldname' => array( 'section' => 'section/subsection',
10 properties... ),
11 ...
15 static $typeMappings = array(
16 'text' => 'HTMLTextField',
17 'select' => 'HTMLSelectField',
18 'radio' => 'HTMLRadioField',
19 'multiselect' => 'HTMLMultiSelectField',
20 'check' => 'HTMLCheckField',
21 'toggle' => 'HTMLCheckField',
22 'int' => 'HTMLIntField',
23 'info' => 'HTMLInfoField',
24 'selectorother' => 'HTMLSelectOrOtherField',
27 function __construct( $descriptor, $messagePrefix ) {
28 $this->mMessagePrefix = $messagePrefix;
30 // Expand out into a tree.
31 $loadedDescriptor = array();
32 $this->mFlatFields = array();
34 foreach( $descriptor as $fieldname => $info ) {
35 $section = '';
36 if ( isset( $info['section'] ) )
37 $section = $info['section'];
39 $info['name'] = $fieldname;
41 $field = $this->loadInputFromParameters( $info );
42 $field->mParent = $this;
44 $setSection =& $loadedDescriptor;
45 if ($section) {
46 $sectionParts = explode( '/', $section );
48 while( count($sectionParts) ) {
49 $newName = array_shift( $sectionParts );
51 if ( !isset($setSection[$newName]) ) {
52 $setSection[$newName] = array();
55 $setSection =& $setSection[$newName];
59 $setSection[$fieldname] = $field;
60 $this->mFlatFields[$fieldname] = $field;
63 $this->mFieldTree = $loadedDescriptor;
65 $this->mShowReset = true;
68 static function addJS() {
69 if (self::$jsAdded) return;
71 global $wgOut, $wgStylePath;
73 $wgOut->addScriptFile( "$wgStylePath/common/htmlform.js" );
76 static function loadInputFromParameters( $descriptor ) {
77 if ( isset( $descriptor['class'] ) ) {
78 $class = $descriptor['class'];
79 } elseif ( isset( $descriptor['type'] ) ) {
80 $class = self::$typeMappings[$descriptor['type']];
81 $descriptor['class'] = $class;
84 if (!$class) {
85 throw new MWException( "Descriptor with no class: ".print_r( $descriptor, true ) );
88 $obj = new $class( $descriptor );
90 return $obj;
93 function show() {
94 $html = '';
96 self::addJS();
98 // Load data from the request.
99 $this->loadData();
101 // Try a submission
102 global $wgUser, $wgRequest;
103 $editToken = $wgRequest->getVal( 'wpEditToken' );
105 $result = false;
106 if ( $wgUser->matchEditToken( $editToken ) )
107 $result = $this->trySubmit();
109 if ($result === true)
110 return $result;
112 // Display form.
113 $this->displayForm( $result );
116 /** Return values:
117 * TRUE == Successful submission
118 * FALSE == No submission attempted
119 * Anything else == Error to display.
121 function trySubmit() {
122 // Check for validation
123 foreach( $this->mFlatFields as $fieldname => $field ) {
124 if ( !empty($field->mParams['nodata']) ) continue;
125 if ( $field->validate( $this->mFieldData[$fieldname],
126 $this->mFieldData ) !== true ) {
127 return isset($this->mValidationErrorMessage) ?
128 $this->mValidationErrorMessage : array( 'htmlform-invalid-input' );
132 $callback = $this->mSubmitCallback;
134 $data = $this->filterDataForSubmit( $this->mFieldData );
136 $res = call_user_func( $callback, $data );
138 return $res;
141 function setSubmitCallback( $cb ) {
142 $this->mSubmitCallback = $cb;
145 function setValidationErrorMessage( $msg ) {
146 $this->mValidationErrorMessage = $msg;
149 function displayForm( $submitResult ) {
150 global $wgOut;
152 if ( $submitResult !== false ) {
153 $this->displayErrors( $submitResult );
156 $html = $this->getBody();
158 // Hidden fields
159 $html .= $this->getHiddenFields();
161 // Buttons
162 $html .= $this->getButtons();
164 $html = $this->wrapForm( $html );
166 $wgOut->addHTML( $html );
169 function wrapForm( $html ) {
170 return Xml::tags( 'form',
171 array(
172 'action' => $this->getTitle()->getFullURL(),
173 'method' => 'post',
175 $html );
178 function getHiddenFields() {
179 global $wgUser;
180 $html = '';
182 $html .= Xml::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
183 $html .= Xml::hidden( 'title', $this->getTitle() ) . "\n";
185 return $html;
188 function getButtons() {
189 $html = '';
191 $attribs = array();
193 if ( isset($this->mSubmitID) )
194 $attribs['id'] = $this->mSubmitID;
196 $attribs['class'] = 'mw-htmlform-submit';
198 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
200 if ($this->mShowReset) {
201 $html .= Xml::element( 'input',
202 array( 'type' => 'reset',
203 'value' => wfMsg('htmlform-reset')
204 ) ) . "\n";
207 return $html;
210 function getBody() {
211 return $this->displaySection( $this->mFieldTree );
214 function displayErrors( $errors ) {
215 if ( is_array( $errors ) ) {
216 $errorstr = $this->formatErrors( $errors );
217 } else {
218 $errorstr = $errors;
221 $errorstr = Xml::tags( 'div', array( 'class' => 'error' ), $errorstr );
223 global $wgOut;
224 $wgOut->addHTML( $errorstr );
227 static function formatErrors( $errors ) {
228 $errorstr = '';
229 foreach ( $errors as $error ) {
230 if (is_array($error)) {
231 $msg = array_shift($error);
232 } else {
233 $msg = $error;
234 $error = array();
236 $errorstr .= Xml::tags( 'li',
237 null,
238 wfMsgExt( $msg, array( 'parseinline' ), $error )
242 $errorstr = Xml::tags( 'ul', null, $errorstr );
244 return $errorstr;
247 function setSubmitText( $t ) {
248 $this->mSubmitText = $t;
251 function getSubmitText() {
252 return isset($this->mSubmitText) ? $this->mSubmitText : wfMsg('htmlform-submit');
255 function setSubmitID( $t ) {
256 $this->mSubmitID = $t;
259 function setMessagePrefix( $p ) {
260 $this->mMessagePrefix = $p;
263 function setTitle( $t ) {
264 $this->mTitle = $t;
267 function getTitle() {
268 return $this->mTitle;
271 function displaySection( $fields ) {
272 $tableHtml = '';
273 $subsectionHtml = '';
274 $hasLeftColumn = false;
276 foreach( $fields as $key => $value ) {
277 if ( is_object( $value ) ) {
278 $v = empty($value->mParams['nodata'])
279 ? $this->mFieldData[$key]
280 : $value->getDefault();
281 $tableHtml .= $value->getTableRow( $v );
283 if ($value->getLabel() != '&nbsp;')
284 $hasLeftColumn = true;
285 } elseif ( is_array( $value ) ) {
286 $section = $this->displaySection( $value );
287 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
288 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
292 $classes = array();
293 if (!$hasLeftColumn) // Avoid strange spacing when no labels exist
294 $classes[] = 'mw-htmlform-nolabel';
295 $classes = implode( ' ', $classes );
297 $tableHtml = "<table class='$classes'><tbody>\n$tableHtml\n</tbody></table>\n";
299 return $subsectionHtml . "\n" . $tableHtml;
302 function loadData() {
303 global $wgRequest;
305 $fieldData = array();
307 foreach( $this->mFlatFields as $fieldname => $field ) {
308 if ( !empty($field->mParams['nodata']) ) continue;
309 if ( !empty($field->mParams['disabled']) ) {
310 $fieldData[$fieldname] = $field->getDefault();
311 } else {
312 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
316 // Filter data.
317 foreach( $fieldData as $name => &$value ) {
318 $field = $this->mFlatFields[$name];
319 $value = $field->filter( $value, $this->mFlatFields );
322 $this->mFieldData = $fieldData;
325 function importData( $fieldData ) {
326 // Filter data.
327 foreach( $fieldData as $name => &$value ) {
328 $field = $this->mFlatFields[$name];
329 $value = $field->filter( $value, $this->mFlatFields );
332 foreach( $this->mFlatFields as $fieldname => $field ) {
333 if ( !isset($fieldData[$fieldname]) )
334 $fieldData[$fieldname] = $field->getDefault();
337 $this->mFieldData = $fieldData;
340 function suppressReset( $suppressReset = true ) {
341 $this->mShowReset = !$suppressReset;
344 function filterDataForSubmit( $data ) {
345 return $data;
349 abstract class HTMLFormField {
350 abstract function getInputHTML( $value );
352 function validate( $value, $alldata ) {
353 if ( isset($this->mValidationCallback) ) {
354 return call_user_func( $this->mValidationCallback, $value, $alldata );
357 return true;
360 function filter( $value, $alldata ) {
361 if( isset( $this->mFilterCallback ) ) {
362 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
365 return $value;
368 function loadDataFromRequest( $request ) {
369 if ($request->getCheck( $this->mName ) ) {
370 return $request->getText( $this->mName );
371 } else {
372 return $this->getDefault();
376 function __construct( $params ) {
377 $this->mParams = $params;
379 if (isset( $params['label-message'] ) ) {
380 $msgInfo = $params['label-message'];
382 if ( is_array( $msgInfo ) ) {
383 $msg = array_shift( $msgInfo );
384 } else {
385 $msg = $msgInfo;
386 $msgInfo = array();
389 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
390 } elseif ( isset($params['label']) ) {
391 $this->mLabel = $params['label'];
394 if ( isset( $params['name'] ) ) {
395 $this->mName = 'wp'.$params['name'];
396 $this->mID = 'mw-input-'.$params['name'];
399 if ( isset( $params['default'] ) ) {
400 $this->mDefault = $params['default'];
403 if ( isset( $params['id'] ) ) {
404 $this->mID = $params['id'];
407 if ( isset( $params['validation-callback'] ) ) {
408 $this->mValidationCallback = $params['validation-callback'];
411 if ( isset( $params['filter-callback'] ) ) {
412 $this->mFilterCallback = $params['filter-callback'];
416 function getTableRow( $value ) {
417 // Check for invalid data.
418 global $wgRequest;
420 $errors = $this->validate( $value, $this->mParent->mFieldData );
421 if ( $errors === true || !$wgRequest->wasPosted() ) {
422 $errors = '';
423 } else {
424 $errors = Xml::tags( 'span', array( 'class' => 'error' ), $errors );
427 $html = '';
429 $html .= Xml::tags( 'td', array( 'class' => 'mw-label' ),
430 Xml::tags( 'label', array( 'for' => $this->mID ), $this->getLabel() )
432 $html .= Xml::tags( 'td', array( 'class' => 'mw-input' ),
433 $this->getInputHTML( $value ) ."\n$errors" );
435 $fieldType = get_class($this);
437 $html = Xml::tags( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
438 $html ) . "\n";
440 // Help text
441 if ( isset($this->mParams['help-message']) ) {
442 $msg = $this->mParams['help-message'];
444 $text = wfMsgExt( $msg, 'parseinline' );
446 if (!wfEmptyMsg( $msg, $text ) ) {
447 $row = Xml::tags( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
448 $text );
450 $row = Xml::tags( 'tr', null, $row );
452 $html .= "$row\n";
456 return $html;
459 function getLabel() {
460 return $this->mLabel;
463 function getDefault() {
464 if ( isset( $this->mDefault ) ) {
465 return $this->mDefault;
466 } else {
467 return null;
471 static function flattenOptions( $options ) {
472 $flatOpts = array();
474 foreach( $options as $key => $value ) {
475 if ( is_array( $value ) ) {
476 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
477 } else {
478 $flatOpts[] = $value;
482 return $flatOpts;
486 class HTMLTextField extends HTMLFormField {
488 function getSize() {
489 return isset($this->mParams['size']) ? $this->mParams['size'] : 45;
492 function getInputHTML( $value ) {
493 $attribs = array( 'id' => $this->mID );
495 if ( isset($this->mParams['maxlength']) ) {
496 $attribs['maxlength'] = $this->mParams['maxlength'];
499 if (!empty($this->mParams['disabled'])) {
500 $attribs['disabled'] = 'disabled';
503 return Xml::input( $this->mName,
504 $this->getSize(),
505 $value,
506 $attribs ) ;
511 class HTMLIntField extends HTMLTextField {
512 function getSize() {
513 return isset($this->mParams['size']) ? $this->mParams['size'] : 20;
516 function validate( $value, $alldata ) {
517 $p = parent::validate($value, $alldata);
519 if ($p !== true) return $p;
521 if ( intval($value) != $value ) {
522 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
525 $in_range = true;
527 if ( isset($this->mParams['min']) ) {
528 $min = $this->mParams['min'];
529 if ( $min > $value )
530 return wfMsgExt( 'htmlform-int-toolow', 'parse', array($min) );
533 if ( isset($this->mParams['max']) ) {
534 $max = $this->mParams['max'];
535 if ($max < $value)
536 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array($max) );
539 return true;
543 class HTMLCheckField extends HTMLFormField {
544 function getInputHTML( $value ) {
545 if ( !empty( $this->mParams['invert'] ) )
546 $value = !$value;
548 $attr = array( 'id' => $this->mID );
549 if (!empty($this->mParams['disabled'])) {
550 $attr['disabled'] = 'disabled';
553 return Xml::check( $this->mName, $value, $attr ) . '&nbsp;' .
554 Xml::tags( 'label', array( 'for' => $this->mID ), $this->mLabel );
557 function getLabel( ) {
558 return '&nbsp;'; // In the right-hand column.
561 function loadDataFromRequest( $request ) {
562 $invert = false;
563 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
564 $invert = true;
567 // GetCheck won't work like we want for checks.
568 if ($request->getCheck( 'wpEditToken' ) ) {
569 // XOR has the following truth table, which is what we want
570 // INVERT VALUE | OUTPUT
571 // true true | false
572 // false true | true
573 // false false | false
574 // true false | true
575 return $request->getBool( $this->mName ) xor $invert;
576 } else {
577 return $this->getDefault();
582 class HTMLSelectField extends HTMLFormField {
584 function validate( $value, $alldata ) {
585 $p = parent::validate( $value, $alldata );
586 if ($p !== true) return $p;
588 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
589 if ( in_array( $value, $validOptions ) )
590 return true;
591 else
592 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
595 function getInputHTML( $value ) {
596 $select = new XmlSelect( $this->mName, $this->mID, $value );
598 if (!empty($this->mParams['disabled'])) {
599 $select->setAttribute( 'disabled', 'disabled' );
602 $select->addOptions( $this->mParams['options'] );
604 return $select->getHTML();
608 class HTMLSelectOrOtherField extends HTMLTextField {
609 static $jsAdded = false;
611 function __construct( $params ) {
612 if (! array_key_exists('other', $params['options']) ) {
613 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
616 parent::__construct( $params );
619 function getInputHTML( $value ) {
620 $valInSelect = false;
622 if ($value !== false)
623 $valInSelect = in_array( $value,
624 HTMLFormField::flattenOptions($this->mParams['options']) );
626 $selected = $valInSelect ? $value : 'other';
628 $select = new XmlSelect( $this->mName, $this->mID, $selected );
629 $select->addOptions( $this->mParams['options'] );
631 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
633 $tbAttribs = array( 'id' => $this->mID.'-other' );
634 if (!empty($this->mParams['disabled'])) {
635 $select->setAttribute( 'disabled', 'disabled' );
636 $tbAttribs['disabled'] = 'disabled';
639 $select = $select->getHTML();
641 if ( isset($this->mParams['maxlength']) ) {
642 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
645 $textbox = Xml::input( $this->mName.'-other',
646 $this->getSize(),
647 $valInSelect ? '' : $value,
648 $tbAttribs );
650 return "$select<br/>\n$textbox";
653 function loadDataFromRequest( $request ) {
654 if ($request->getCheck( $this->mName ) ) {
655 $val = $request->getText( $this->mName );
657 if ($val == 'other') {
658 $val = $request->getText( $this->mName.'-other' );
661 return $val;
662 } else {
663 return $this->getDefault();
668 class HTMLMultiSelectField extends HTMLFormField {
669 function validate( $value, $alldata ) {
670 $p = parent::validate( $value, $alldata );
671 if ($p !== true) return $p;
673 if (!is_array($value)) return false;
675 // If all options are valid, array_intersect of the valid options and the provided
676 // options will return the provided options.
677 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
679 $validValues = array_intersect( $value, $validOptions );
680 if ( count( $validValues ) == count($value) )
681 return true;
682 else
683 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
686 function getInputHTML( $value ) {
687 $html = $this->formatOptions( $this->mParams['options'], $value );
689 return $html;
692 function formatOptions( $options, $value ) {
693 $html = '';
695 $attribs = array();
696 if ( !empty( $this->mParams['disabled'] ) ) {
697 $attribs['disabled'] = 'disabled';
700 foreach( $options as $label => $info ) {
701 if (is_array($info)) {
702 $html .= Xml::tags( 'h1', null, $label ) . "\n";
703 $html .= $this->formatOptions( $info, $value );
704 } else {
705 $thisAttribs = array( 'id' => $this->mID."-$info", 'value' => $info );
707 $checkbox = Xml::check( $this->mName.'[]', in_array( $info, $value ),
708 $attribs + $thisAttribs );
709 $checkbox .= '&nbsp;' . Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
711 $html .= $checkbox . '<br />';
715 return $html;
718 function loadDataFromRequest( $request ) {
719 // won't work with getCheck
720 if ($request->getCheck( 'wpEditToken' ) ) {
721 $arr = $request->getArray( $this->mName );
723 if (!$arr)
724 $arr = array();
726 return $arr;
727 } else {
728 return $this->getDefault();
732 function getDefault() {
733 if ( isset( $this->mDefault ) ) {
734 return $this->mDefault;
735 } else {
736 return array();
741 class HTMLRadioField extends HTMLFormField {
742 function validate( $value, $alldata ) {
743 $p = parent::validate( $value, $alldata );
744 if ($p !== true) return $p;
746 if (!is_string($value) && !is_int($value))
747 return false;
749 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
751 if ( in_array( $value, $validOptions ) )
752 return true;
753 else
754 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
757 function getInputHTML( $value ) {
758 $html = $this->formatOptions( $this->mParams['options'], $value );
760 return $html;
763 function formatOptions( $options, $value ) {
764 $html = '';
766 $attribs = array();
767 if ( !empty( $this->mParams['disabled'] ) ) {
768 $attribs['disabled'] = 'disabled';
771 foreach( $options as $label => $info ) {
772 if (is_array($info)) {
773 $html .= Xml::tags( 'h1', null, $label ) . "\n";
774 $html .= $this->formatOptions( $info, $value );
775 } else {
776 $html .= Xml::radio( $this->mName, $info, $info == $value,
777 $attribs + array( 'id' => $this->mID."-$info" ) );
778 $html .= '&nbsp;' .
779 Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
781 $html .= "<br/>\n";
785 return $html;
789 class HTMLInfoField extends HTMLFormField {
790 function __construct( $info ) {
791 $info['nodata'] = true;
793 parent::__construct($info);
796 function getInputHTML( $value ) {
797 return !empty($this->mParams['raw']) ? $value : htmlspecialchars($value);
800 function getTableRow( $value ) {
801 if ( !empty($this->mParams['rawrow']) ) {
802 return $value;
805 return parent::getTableRow( $value );