* replace some use of deprecated makeKnownLinkObj() by link() in core
[mediawiki.git] / includes / HTMLForm.php
blob04b36daae4ac3b405a2542efe2cb2ce50a83b7bb
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 setIntro( $msg ) {
150 $this->mIntro = $msg;
153 function displayForm( $submitResult ) {
154 global $wgOut;
156 if ( $submitResult !== false ) {
157 $this->displayErrors( $submitResult );
160 if ( isset($this->mIntro) ) {
161 $wgOut->addHTML( $this->mIntro );
164 $html = $this->getBody();
166 // Hidden fields
167 $html .= $this->getHiddenFields();
169 // Buttons
170 $html .= $this->getButtons();
172 $html = $this->wrapForm( $html );
174 $wgOut->addHTML( $html );
177 function wrapForm( $html ) {
178 return Xml::tags( 'form',
179 array(
180 'action' => $this->getTitle()->getFullURL(),
181 'method' => 'post',
183 $html );
186 function getHiddenFields() {
187 global $wgUser;
188 $html = '';
190 $html .= Xml::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
191 $html .= Xml::hidden( 'title', $this->getTitle() ) . "\n";
193 return $html;
196 function getButtons() {
197 $html = '';
199 $attribs = array();
201 if ( isset($this->mSubmitID) )
202 $attribs['id'] = $this->mSubmitID;
204 $attribs['class'] = 'mw-htmlform-submit';
206 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
208 if ($this->mShowReset) {
209 $html .= Xml::element( 'input',
210 array( 'type' => 'reset',
211 'value' => wfMsg('htmlform-reset')
212 ) ) . "\n";
215 return $html;
218 function getBody() {
219 return $this->displaySection( $this->mFieldTree );
222 function displayErrors( $errors ) {
223 if ( is_array( $errors ) ) {
224 $errorstr = $this->formatErrors( $errors );
225 } else {
226 $errorstr = $errors;
229 $errorstr = Xml::tags( 'div', array( 'class' => 'error' ), $errorstr );
231 global $wgOut;
232 $wgOut->addHTML( $errorstr );
235 static function formatErrors( $errors ) {
236 $errorstr = '';
237 foreach ( $errors as $error ) {
238 if (is_array($error)) {
239 $msg = array_shift($error);
240 } else {
241 $msg = $error;
242 $error = array();
244 $errorstr .= Xml::tags( 'li',
245 null,
246 wfMsgExt( $msg, array( 'parseinline' ), $error )
250 $errorstr = Xml::tags( 'ul', null, $errorstr );
252 return $errorstr;
255 function setSubmitText( $t ) {
256 $this->mSubmitText = $t;
259 function getSubmitText() {
260 return isset($this->mSubmitText) ? $this->mSubmitText : wfMsg('htmlform-submit');
263 function setSubmitID( $t ) {
264 $this->mSubmitID = $t;
267 function setMessagePrefix( $p ) {
268 $this->mMessagePrefix = $p;
271 function setTitle( $t ) {
272 $this->mTitle = $t;
275 function getTitle() {
276 return $this->mTitle;
279 function displaySection( $fields ) {
280 $tableHtml = '';
281 $subsectionHtml = '';
282 $hasLeftColumn = false;
284 foreach( $fields as $key => $value ) {
285 if ( is_object( $value ) ) {
286 $v = empty($value->mParams['nodata'])
287 ? $this->mFieldData[$key]
288 : $value->getDefault();
289 $tableHtml .= $value->getTableRow( $v );
291 if ($value->getLabel() != '&nbsp;')
292 $hasLeftColumn = true;
293 } elseif ( is_array( $value ) ) {
294 $section = $this->displaySection( $value );
295 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
296 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
300 $classes = array();
301 if (!$hasLeftColumn) // Avoid strange spacing when no labels exist
302 $classes[] = 'mw-htmlform-nolabel';
303 $classes = implode( ' ', $classes );
305 $tableHtml = "<table class='$classes'><tbody>\n$tableHtml\n</tbody></table>\n";
307 return $subsectionHtml . "\n" . $tableHtml;
310 function loadData() {
311 global $wgRequest;
313 $fieldData = array();
315 foreach( $this->mFlatFields as $fieldname => $field ) {
316 if ( !empty($field->mParams['nodata']) ) continue;
317 if ( !empty($field->mParams['disabled']) ) {
318 $fieldData[$fieldname] = $field->getDefault();
319 } else {
320 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
324 // Filter data.
325 foreach( $fieldData as $name => &$value ) {
326 $field = $this->mFlatFields[$name];
327 $value = $field->filter( $value, $this->mFlatFields );
330 $this->mFieldData = $fieldData;
333 function importData( $fieldData ) {
334 // Filter data.
335 foreach( $fieldData as $name => &$value ) {
336 $field = $this->mFlatFields[$name];
337 $value = $field->filter( $value, $this->mFlatFields );
340 foreach( $this->mFlatFields as $fieldname => $field ) {
341 if ( !isset($fieldData[$fieldname]) )
342 $fieldData[$fieldname] = $field->getDefault();
345 $this->mFieldData = $fieldData;
348 function suppressReset( $suppressReset = true ) {
349 $this->mShowReset = !$suppressReset;
352 function filterDataForSubmit( $data ) {
353 return $data;
357 abstract class HTMLFormField {
358 abstract function getInputHTML( $value );
360 function validate( $value, $alldata ) {
361 if ( isset($this->mValidationCallback) ) {
362 return call_user_func( $this->mValidationCallback, $value, $alldata );
365 return true;
368 function filter( $value, $alldata ) {
369 if( isset( $this->mFilterCallback ) ) {
370 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
373 return $value;
376 function loadDataFromRequest( $request ) {
377 if ($request->getCheck( $this->mName ) ) {
378 return $request->getText( $this->mName );
379 } else {
380 return $this->getDefault();
384 function __construct( $params ) {
385 $this->mParams = $params;
387 if (isset( $params['label-message'] ) ) {
388 $msgInfo = $params['label-message'];
390 if ( is_array( $msgInfo ) ) {
391 $msg = array_shift( $msgInfo );
392 } else {
393 $msg = $msgInfo;
394 $msgInfo = array();
397 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
398 } elseif ( isset($params['label']) ) {
399 $this->mLabel = $params['label'];
402 if ( isset( $params['name'] ) ) {
403 $this->mName = 'wp'.$params['name'];
404 $this->mID = 'mw-input-'.$params['name'];
407 if ( isset( $params['default'] ) ) {
408 $this->mDefault = $params['default'];
411 if ( isset( $params['id'] ) ) {
412 $this->mID = $params['id'];
415 if ( isset( $params['validation-callback'] ) ) {
416 $this->mValidationCallback = $params['validation-callback'];
419 if ( isset( $params['filter-callback'] ) ) {
420 $this->mFilterCallback = $params['filter-callback'];
424 function getTableRow( $value ) {
425 // Check for invalid data.
426 global $wgRequest;
428 $errors = $this->validate( $value, $this->mParent->mFieldData );
429 if ( $errors === true || !$wgRequest->wasPosted() ) {
430 $errors = '';
431 } else {
432 $errors = Xml::tags( 'span', array( 'class' => 'error' ), $errors );
435 $html = '';
437 $html .= Xml::tags( 'td', array( 'class' => 'mw-label' ),
438 Xml::tags( 'label', array( 'for' => $this->mID ), $this->getLabel() )
440 $html .= Xml::tags( 'td', array( 'class' => 'mw-input' ),
441 $this->getInputHTML( $value ) ."\n$errors" );
443 $fieldType = get_class($this);
445 $html = Xml::tags( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
446 $html ) . "\n";
448 // Help text
449 if ( isset($this->mParams['help-message']) ) {
450 $msg = $this->mParams['help-message'];
452 $text = wfMsgExt( $msg, 'parseinline' );
454 if (!wfEmptyMsg( $msg, $text ) ) {
455 $row = Xml::tags( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
456 $text );
458 $row = Xml::tags( 'tr', null, $row );
460 $html .= "$row\n";
464 return $html;
467 function getLabel() {
468 return $this->mLabel;
471 function getDefault() {
472 if ( isset( $this->mDefault ) ) {
473 return $this->mDefault;
474 } else {
475 return null;
479 static function flattenOptions( $options ) {
480 $flatOpts = array();
482 foreach( $options as $key => $value ) {
483 if ( is_array( $value ) ) {
484 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
485 } else {
486 $flatOpts[] = $value;
490 return $flatOpts;
494 class HTMLTextField extends HTMLFormField {
496 function getSize() {
497 return isset($this->mParams['size']) ? $this->mParams['size'] : 45;
500 function getInputHTML( $value ) {
501 $attribs = array( 'id' => $this->mID );
503 if ( isset($this->mParams['maxlength']) ) {
504 $attribs['maxlength'] = $this->mParams['maxlength'];
507 if (!empty($this->mParams['disabled'])) {
508 $attribs['disabled'] = 'disabled';
511 return Xml::input( $this->mName,
512 $this->getSize(),
513 $value,
514 $attribs ) ;
519 class HTMLIntField extends HTMLTextField {
520 function getSize() {
521 return isset($this->mParams['size']) ? $this->mParams['size'] : 20;
524 function validate( $value, $alldata ) {
525 $p = parent::validate($value, $alldata);
527 if ($p !== true) return $p;
529 if ( intval($value) != $value ) {
530 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
533 $in_range = true;
535 if ( isset($this->mParams['min']) ) {
536 $min = $this->mParams['min'];
537 if ( $min > $value )
538 return wfMsgExt( 'htmlform-int-toolow', 'parse', array($min) );
541 if ( isset($this->mParams['max']) ) {
542 $max = $this->mParams['max'];
543 if ($max < $value)
544 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array($max) );
547 return true;
551 class HTMLCheckField extends HTMLFormField {
552 function getInputHTML( $value ) {
553 if ( !empty( $this->mParams['invert'] ) )
554 $value = !$value;
556 $attr = array( 'id' => $this->mID );
557 if (!empty($this->mParams['disabled'])) {
558 $attr['disabled'] = 'disabled';
561 return Xml::check( $this->mName, $value, $attr ) . '&nbsp;' .
562 Xml::tags( 'label', array( 'for' => $this->mID ), $this->mLabel );
565 function getLabel( ) {
566 return '&nbsp;'; // In the right-hand column.
569 function loadDataFromRequest( $request ) {
570 $invert = false;
571 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
572 $invert = true;
575 // GetCheck won't work like we want for checks.
576 if ($request->getCheck( 'wpEditToken' ) ) {
577 // XOR has the following truth table, which is what we want
578 // INVERT VALUE | OUTPUT
579 // true true | false
580 // false true | true
581 // false false | false
582 // true false | true
583 return $request->getBool( $this->mName ) xor $invert;
584 } else {
585 return $this->getDefault();
590 class HTMLSelectField extends HTMLFormField {
592 function validate( $value, $alldata ) {
593 $p = parent::validate( $value, $alldata );
594 if ($p !== true) return $p;
596 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
597 if ( in_array( $value, $validOptions ) )
598 return true;
599 else
600 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
603 function getInputHTML( $value ) {
604 $select = new XmlSelect( $this->mName, $this->mID, $value );
606 if (!empty($this->mParams['disabled'])) {
607 $select->setAttribute( 'disabled', 'disabled' );
610 $select->addOptions( $this->mParams['options'] );
612 return $select->getHTML();
616 class HTMLSelectOrOtherField extends HTMLTextField {
617 static $jsAdded = false;
619 function __construct( $params ) {
620 if (! array_key_exists('other', $params['options']) ) {
621 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
624 parent::__construct( $params );
627 function getInputHTML( $value ) {
628 $valInSelect = false;
630 if ($value !== false)
631 $valInSelect = in_array( $value,
632 HTMLFormField::flattenOptions($this->mParams['options']) );
634 $selected = $valInSelect ? $value : 'other';
636 $select = new XmlSelect( $this->mName, $this->mID, $selected );
637 $select->addOptions( $this->mParams['options'] );
639 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
641 $tbAttribs = array( 'id' => $this->mID.'-other' );
642 if (!empty($this->mParams['disabled'])) {
643 $select->setAttribute( 'disabled', 'disabled' );
644 $tbAttribs['disabled'] = 'disabled';
647 $select = $select->getHTML();
649 if ( isset($this->mParams['maxlength']) ) {
650 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
653 $textbox = Xml::input( $this->mName.'-other',
654 $this->getSize(),
655 $valInSelect ? '' : $value,
656 $tbAttribs );
658 return "$select<br/>\n$textbox";
661 function loadDataFromRequest( $request ) {
662 if ($request->getCheck( $this->mName ) ) {
663 $val = $request->getText( $this->mName );
665 if ($val == 'other') {
666 $val = $request->getText( $this->mName.'-other' );
669 return $val;
670 } else {
671 return $this->getDefault();
676 class HTMLMultiSelectField extends HTMLFormField {
677 function validate( $value, $alldata ) {
678 $p = parent::validate( $value, $alldata );
679 if ($p !== true) return $p;
681 if (!is_array($value)) return false;
683 // If all options are valid, array_intersect of the valid options and the provided
684 // options will return the provided options.
685 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
687 $validValues = array_intersect( $value, $validOptions );
688 if ( count( $validValues ) == count($value) )
689 return true;
690 else
691 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
694 function getInputHTML( $value ) {
695 $html = $this->formatOptions( $this->mParams['options'], $value );
697 return $html;
700 function formatOptions( $options, $value ) {
701 $html = '';
703 $attribs = array();
704 if ( !empty( $this->mParams['disabled'] ) ) {
705 $attribs['disabled'] = 'disabled';
708 foreach( $options as $label => $info ) {
709 if (is_array($info)) {
710 $html .= Xml::tags( 'h1', null, $label ) . "\n";
711 $html .= $this->formatOptions( $info, $value );
712 } else {
713 $thisAttribs = array( 'id' => $this->mID."-$info", 'value' => $info );
715 $checkbox = Xml::check( $this->mName.'[]', in_array( $info, $value ),
716 $attribs + $thisAttribs );
717 $checkbox .= '&nbsp;' . Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
719 $html .= $checkbox . '<br />';
723 return $html;
726 function loadDataFromRequest( $request ) {
727 // won't work with getCheck
728 if ($request->getCheck( 'wpEditToken' ) ) {
729 $arr = $request->getArray( $this->mName );
731 if (!$arr)
732 $arr = array();
734 return $arr;
735 } else {
736 return $this->getDefault();
740 function getDefault() {
741 if ( isset( $this->mDefault ) ) {
742 return $this->mDefault;
743 } else {
744 return array();
749 class HTMLRadioField extends HTMLFormField {
750 function validate( $value, $alldata ) {
751 $p = parent::validate( $value, $alldata );
752 if ($p !== true) return $p;
754 if (!is_string($value) && !is_int($value))
755 return false;
757 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
759 if ( in_array( $value, $validOptions ) )
760 return true;
761 else
762 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
765 function getInputHTML( $value ) {
766 $html = $this->formatOptions( $this->mParams['options'], $value );
768 return $html;
771 function formatOptions( $options, $value ) {
772 $html = '';
774 $attribs = array();
775 if ( !empty( $this->mParams['disabled'] ) ) {
776 $attribs['disabled'] = 'disabled';
779 foreach( $options as $label => $info ) {
780 if (is_array($info)) {
781 $html .= Xml::tags( 'h1', null, $label ) . "\n";
782 $html .= $this->formatOptions( $info, $value );
783 } else {
784 $html .= Xml::radio( $this->mName, $info, $info == $value,
785 $attribs + array( 'id' => $this->mID."-$info" ) );
786 $html .= '&nbsp;' .
787 Xml::tags( 'label', array( 'for' => $this->mID."-$info" ), $label );
789 $html .= "<br/>\n";
793 return $html;
797 class HTMLInfoField extends HTMLFormField {
798 function __construct( $info ) {
799 $info['nodata'] = true;
801 parent::__construct($info);
804 function getInputHTML( $value ) {
805 return !empty($this->mParams['raw']) ? $value : htmlspecialchars($value);
808 function getTableRow( $value ) {
809 if ( !empty($this->mParams['rawrow']) ) {
810 return $value;
813 return parent::getTableRow( $value );