Recommit r56947, partially overwritten in r57024.
[lhc/web/wiklou.git] / includes / HTMLForm.php
1 <?php
2
3 /**
4 * Object handling generic submission, CSRF protection, layout and
5 * other logic for UI forms. in a reusable manner.
6 *
7 * In order to generate the form, the HTMLForm object takes an array
8 * structure detailing the form fields available. Each element of the
9 * array is a basic property-list, including the type of field, the
10 * label it is to be given in the form, callbacks for validation and
11 * 'filtering', and other pertinent information.
12 *
13 * Field types are implemented as subclasses of the generic HTMLFormField
14 * object, and typically implement at least getInputHTML, which generates
15 * the HTML for the input field to be placed in the table.
16 *
17 * The constructor input is an associative array of $fieldname => $info,
18 * where $info is an Associative Array with any of the following:
19 *
20 * 'class' -- the subclass of HTMLFormField that will be used
21 * to create the object. *NOT* the CSS class!
22 * 'type' -- roughly translates into the <select> type attribute.
23 * if 'class' is not specified, this is used as a map
24 * through HTMLForm::$typeMappings to get the class name.
25 * 'default' -- default value when the form is displayed
26 * 'id' -- HTML id attribute
27 * 'options' -- varies according to the specific object.
28 * 'label-message' -- message key for a message to use as the label.
29 * can be an array of msg key and then parameters to
30 * the message.
31 * 'label' -- alternatively, a raw text message. Overridden by
32 * label-message
33 * 'help-message' -- message key for a message to use as a help text.
34 * can be an array of msg key and then parameters to
35 * the message.
36 * 'required' -- passed through to the object, indicating that it
37 * is a required field.
38 * 'size' -- the length of text fields
39 * 'filter-callback -- a function name to give you the chance to
40 * massage the inputted value before it's processed.
41 * @see HTMLForm::filter()
42 * 'validation-callback' -- a function name to give you the chance
43 * to impose extra validation on the field input.
44 * @see HTMLForm::validate()
45 *
46 * TODO: Document 'section' / 'subsection' stuff
47 */
48 class HTMLForm {
49 static $jsAdded = false;
50
51 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
52 static $typeMappings = array(
53 'text' => 'HTMLTextField',
54 'select' => 'HTMLSelectField',
55 'radio' => 'HTMLRadioField',
56 'multiselect' => 'HTMLMultiSelectField',
57 'check' => 'HTMLCheckField',
58 'toggle' => 'HTMLCheckField',
59 'int' => 'HTMLIntField',
60 'float' => 'HTMLFloatField',
61 'info' => 'HTMLInfoField',
62 'selectorother' => 'HTMLSelectOrOtherField',
63 'submit' => 'HTMLSubmitField',
64 'hidden' => 'HTMLHiddenField',
65
66 # HTMLTextField will output the correct type="" attribute automagically.
67 # There are about four zillion other HTML 5 input types, like url, but
68 # we don't use those at the moment, so no point in adding all of them.
69 'email' => 'HTMLTextField',
70 'password' => 'HTMLTextField',
71 );
72
73 protected $mMessagePrefix;
74 protected $mFlatFields;
75 protected $mFieldTree;
76 protected $mShowReset = false;
77 public $mFieldData;
78
79 protected $mSubmitCallback;
80 protected $mValidationErrorMessage;
81
82 protected $mPre = '';
83 protected $mHeader = '';
84 protected $mPost = '';
85
86 protected $mSubmitID;
87 protected $mSubmitText;
88 protected $mTitle;
89
90 protected $mHiddenFields = array();
91 protected $mButtons = array();
92
93 protected $mWrapperLegend = false;
94
95 /**
96 * Build a new HTMLForm from an array of field attributes
97 * @param $descriptor Array of Field constructs, as described above
98 * @param $messagePrefix String a prefix to go in front of default messages
99 */
100 public function __construct( $descriptor, $messagePrefix='' ) {
101 $this->mMessagePrefix = $messagePrefix;
102
103 // Expand out into a tree.
104 $loadedDescriptor = array();
105 $this->mFlatFields = array();
106
107 foreach( $descriptor as $fieldname => $info ) {
108 $section = '';
109 if ( isset( $info['section'] ) )
110 $section = $info['section'];
111
112 $info['name'] = $fieldname;
113
114 $field = self::loadInputFromParameters( $info );
115 $field->mParent = $this;
116
117 $setSection =& $loadedDescriptor;
118 if( $section ) {
119 $sectionParts = explode( '/', $section );
120
121 while( count( $sectionParts ) ) {
122 $newName = array_shift( $sectionParts );
123
124 if ( !isset( $setSection[$newName] ) ) {
125 $setSection[$newName] = array();
126 }
127
128 $setSection =& $setSection[$newName];
129 }
130 }
131
132 $setSection[$fieldname] = $field;
133 $this->mFlatFields[$fieldname] = $field;
134 }
135
136 $this->mFieldTree = $loadedDescriptor;
137 }
138
139 /**
140 * Add the HTMLForm-specific JavaScript, if it hasn't been
141 * done already.
142 */
143 static function addJS() {
144 if( self::$jsAdded ) return;
145
146 global $wgOut;
147
148 $wgOut->addScriptClass( 'htmlform' );
149 }
150
151 /**
152 * Initialise a new Object for the field
153 * @param $descriptor input Descriptor, as described above
154 * @return HTMLFormField subclass
155 */
156 static function loadInputFromParameters( $descriptor ) {
157 if ( isset( $descriptor['class'] ) ) {
158 $class = $descriptor['class'];
159 } elseif ( isset( $descriptor['type'] ) ) {
160 $class = self::$typeMappings[$descriptor['type']];
161 $descriptor['class'] = $class;
162 }
163
164 if( !$class ) {
165 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
166 }
167
168 $obj = new $class( $descriptor );
169
170 return $obj;
171 }
172
173 /**
174 * The here's-one-I-made-earlier option: do the submission if
175 * posted, or display the form with or without funky valiation
176 * errors
177 * @return Bool whether submission was successful.
178 */
179 function show() {
180 $html = '';
181
182 self::addJS();
183
184 # Load data from the request.
185 $this->loadData();
186
187 # Try a submission
188 global $wgUser, $wgRequest;
189 $editToken = $wgRequest->getVal( 'wpEditToken' );
190
191 $result = false;
192 if ( $wgUser->matchEditToken( $editToken ) )
193 $result = $this->trySubmit();
194
195 if( $result === true )
196 return $result;
197
198 # Display form.
199 $this->displayForm( $result );
200 return false;
201 }
202
203 /**
204 * Validate all the fields, and call the submision callback
205 * function if everything is kosher.
206 * @return Mixed Bool true == Successful submission, Bool false
207 * == No submission attempted, anything else == Error to
208 * display.
209 */
210 function trySubmit() {
211 # Check for validation
212 foreach( $this->mFlatFields as $fieldname => $field ) {
213 if ( !empty( $field->mParams['nodata'] ) )
214 continue;
215 if ( $field->validate(
216 $this->mFieldData[$fieldname],
217 $this->mFieldData )
218 !== true )
219 {
220 return isset( $this->mValidationErrorMessage )
221 ? $this->mValidationErrorMessage
222 : array( 'htmlform-invalid-input' );
223 }
224 }
225
226 $callback = $this->mSubmitCallback;
227
228 $data = $this->filterDataForSubmit( $this->mFieldData );
229
230 $res = call_user_func( $callback, $data );
231
232 return $res;
233 }
234
235 /**
236 * Set a callback to a function to do something with the form
237 * once it's been successfully validated.
238 * @param $cb String function name. The function will be passed
239 * the output from HTMLForm::filterDataForSubmit, and must
240 * return Bool true on success, Bool false if no submission
241 * was attempted, or String HTML output to display on error.
242 */
243 function setSubmitCallback( $cb ) {
244 $this->mSubmitCallback = $cb;
245 }
246
247 /**
248 * Set a message to display on a validation error.
249 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
250 * (so each entry can be either a String or Array)
251 */
252 function setValidationErrorMessage( $msg ) {
253 $this->mValidationErrorMessage = $msg;
254 }
255
256 /**
257 * Set the introductory message, overwriting any existing message.
258 * @param $msg String complete text of message to display
259 */
260 function setIntro( $msg ) { $this->mPre = $msg; }
261
262 /**
263 * Add introductory text.
264 * @param $msg String complete text of message to display
265 */
266 function addPreText( $msg ) { $this->mPre .= $msg; }
267
268 /**
269 * Add header text, inside the form.
270 * @param $msg String complete text of message to display
271 */
272 function addHeaderText( $msg ) { $this->mHeader .= $msg; }
273
274 /**
275 * Add text to the end of the display.
276 * @param $msg String complete text of message to display
277 */
278 function addPostText( $msg ) { $this->mPost .= $msg; }
279
280 /**
281 * Add a hidden field to the output
282 * @param $name String field name
283 * @param $value String field value
284 */
285 public function addHiddenField( $name, $value ){
286 $this->mHiddenFields[ $name ] = $value;
287 }
288
289 public function addButton( $name, $value, $id=null ){
290 $this->mButtons[] = compact( 'name', 'value', 'id' );
291 }
292
293 /**
294 * Display the form (sending to wgOut), with an appropriate error
295 * message or stack of messages, and any validation errors, etc.
296 * @param $submitResult Mixed output from HTMLForm::trySubmit()
297 */
298 function displayForm( $submitResult ) {
299 global $wgOut;
300
301 if ( $submitResult !== false ) {
302 $this->displayErrors( $submitResult );
303 }
304
305 $html = ''
306 . $this->mHeader
307 . $this->getBody()
308 . $this->getHiddenFields()
309 . $this->getButtons()
310 ;
311
312 $html = $this->wrapForm( $html );
313
314 $wgOut->addHTML( ''
315 . $this->mPre
316 . $html
317 . $this->mPost
318 );
319 }
320
321 /**
322 * Wrap the form innards in an actual <form> element
323 * @param $html String HTML contents to wrap.
324 * @return String wrapped HTML.
325 */
326 function wrapForm( $html ) {
327
328 # Include a <fieldset> wrapper for style, if requested.
329 if( $this->mWrapperLegend !== false ){
330 $html = Xml::fieldset( $this->mWrapperLegend, $html );
331 }
332
333 return Html::rawElement(
334 'form',
335 array(
336 'action' => $this->getTitle()->getFullURL(),
337 'method' => 'post',
338 'class' => 'visualClear',
339 ),
340 $html
341 );
342 }
343
344 /**
345 * Get the hidden fields that should go inside the form.
346 * @return String HTML.
347 */
348 function getHiddenFields() {
349 global $wgUser;
350 $html = '';
351
352 $html .= Html::hidden( 'wpEditToken', $wgUser->editToken() ) . "\n";
353 $html .= Html::hidden( 'title', $this->getTitle() ) . "\n";
354
355 foreach( $this->mHiddenFields as $name => $value ){
356 $html .= Html::hidden( $name, $value ) . "\n";
357 }
358
359 return $html;
360 }
361
362 /**
363 * Get the submit and (potentially) reset buttons.
364 * @return String HTML.
365 */
366 function getButtons() {
367 $html = '';
368
369 $attribs = array();
370
371 if ( isset( $this->mSubmitID ) )
372 $attribs['id'] = $this->mSubmitID;
373
374 $attribs['class'] = 'mw-htmlform-submit';
375
376 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
377
378 if( $this->mShowReset ) {
379 $html .= Html::element(
380 'input',
381 array(
382 'type' => 'reset',
383 'value' => wfMsg( 'htmlform-reset' )
384 )
385 ) . "\n";
386 }
387
388 foreach( $this->mButtons as $button ){
389 $attrs = array(
390 'type' => 'submit',
391 'name' => $button['name'],
392 'value' => $button['value']
393 );
394 if( isset( $button['id'] ) )
395 $attrs['id'] = $button['id'];
396 $html .= Html::element( 'input', $attrs );
397 }
398
399 return $html;
400 }
401
402 /**
403 * Get the whole body of the form.
404 */
405 function getBody() {
406 return $this->displaySection( $this->mFieldTree );
407 }
408
409 /**
410 * Format and display an error message stack.
411 * @param $errors Mixed String or Array of message keys
412 */
413 function displayErrors( $errors ) {
414 if ( is_array( $errors ) ) {
415 $errorstr = $this->formatErrors( $errors );
416 } else {
417 $errorstr = $errors;
418 }
419
420 $errorstr = Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr );
421
422 global $wgOut;
423 $wgOut->addHTML( $errorstr );
424 }
425
426 /**
427 * Format a stack of error messages into a single HTML string
428 * @param $errors Array of message keys/values
429 * @return String HTML, a <ul> list of errors
430 */
431 static function formatErrors( $errors ) {
432 $errorstr = '';
433 foreach ( $errors as $error ) {
434 if( is_array( $error ) ) {
435 $msg = array_shift( $error );
436 } else {
437 $msg = $error;
438 $error = array();
439 }
440 $errorstr .= Html::rawElement(
441 'li',
442 null,
443 wfMsgExt( $msg, array( 'parseinline' ), $error )
444 );
445 }
446
447 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
448
449 return $errorstr;
450 }
451
452 /**
453 * Set the text for the submit button
454 * @param $t String plaintext.
455 */
456 function setSubmitText( $t ) {
457 $this->mSubmitText = $t;
458 }
459
460 /**
461 * Get the text for the submit button, either customised or a default.
462 * @return unknown_type
463 */
464 function getSubmitText() {
465 return $this->mSubmitText
466 ? $this->mSubmitText
467 : wfMsg( 'htmlform-submit' );
468 }
469
470 /**
471 * Set the id for the submit button.
472 * @param $t String. FIXME: Integrity is *not* validated
473 */
474 function setSubmitID( $t ) {
475 $this->mSubmitID = $t;
476 }
477
478 /**
479 * Prompt the whole form to be wrapped in a <fieldset>, with
480 * this text as its <legend> element.
481 * @param $legend String HTML to go inside the <legend> element.
482 * Will be escaped
483 */
484 public function setWrapperLegend( $legend ){ $this->mWrapperLegend = $legend; }
485
486 /**
487 * Set the prefix for various default messages
488 * TODO: currently only used for the <fieldset> legend on forms
489 * with multiple sections; should be used elsewhre?
490 * @param $p String
491 */
492 function setMessagePrefix( $p ) {
493 $this->mMessagePrefix = $p;
494 }
495
496 /**
497 * Set the title for form submission
498 * @param $t Title of page the form is on/should be posted to
499 */
500 function setTitle( $t ) {
501 $this->mTitle = $t;
502 }
503
504 /**
505 * Get the title
506 * @return Title
507 */
508 function getTitle() {
509 return $this->mTitle;
510 }
511
512 /**
513 * TODO: Document
514 * @param $fields
515 */
516 function displaySection( $fields ) {
517 $tableHtml = '';
518 $subsectionHtml = '';
519 $hasLeftColumn = false;
520
521 foreach( $fields as $key => $value ) {
522 if ( is_object( $value ) ) {
523 $v = empty( $value->mParams['nodata'] )
524 ? $this->mFieldData[$key]
525 : $value->getDefault();
526 $tableHtml .= $value->getTableRow( $v );
527
528 if( $value->getLabel() != '&nbsp;' )
529 $hasLeftColumn = true;
530 } elseif ( is_array( $value ) ) {
531 $section = $this->displaySection( $value );
532 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
533 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
534 }
535 }
536
537 $classes = array();
538 if( !$hasLeftColumn ) // Avoid strange spacing when no labels exist
539 $classes[] = 'mw-htmlform-nolabel';
540 $classes = implode( ' ', $classes );
541
542 $tableHtml = Html::rawElement( 'table', array( 'class' => $classes ),
543 Html::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
544
545 return $subsectionHtml . "\n" . $tableHtml;
546 }
547
548 /**
549 * Construct the form fields from the Descriptor array
550 */
551 function loadData() {
552 global $wgRequest;
553
554 $fieldData = array();
555
556 foreach( $this->mFlatFields as $fieldname => $field ) {
557 if ( !empty( $field->mParams['nodata'] ) ) continue;
558 if ( !empty( $field->mParams['disabled'] ) ) {
559 $fieldData[$fieldname] = $field->getDefault();
560 } else {
561 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
562 }
563 }
564
565 # Filter data.
566 foreach( $fieldData as $name => &$value ) {
567 $field = $this->mFlatFields[$name];
568 $value = $field->filter( $value, $this->mFlatFields );
569 }
570
571 $this->mFieldData = $fieldData;
572 }
573
574 /**
575 * Stop a reset button being shown for this form
576 * @param $suppressReset Bool set to false to re-enable the
577 * button again
578 */
579 function suppressReset( $suppressReset = true ) {
580 $this->mShowReset = !$suppressReset;
581 }
582
583 /**
584 * Overload this if you want to apply special filtration routines
585 * to the form as a whole, after it's submitted but before it's
586 * processed.
587 * @param $data
588 * @return unknown_type
589 */
590 function filterDataForSubmit( $data ) {
591 return $data;
592 }
593 }
594
595 /**
596 * The parent class to generate form fields. Any field type should
597 * be a subclass of this.
598 */
599 abstract class HTMLFormField {
600
601 protected $mValidationCallback;
602 protected $mFilterCallback;
603 protected $mName;
604 public $mParams;
605 protected $mLabel; # String label. Set on construction
606 protected $mID;
607 protected $mDefault;
608 public $mParent;
609
610 /**
611 * This function must be implemented to return the HTML to generate
612 * the input object itself. It should not implement the surrounding
613 * table cells/rows, or labels/help messages.
614 * @param $value String the value to set the input to; eg a default
615 * text for a text input.
616 * @return String valid HTML.
617 */
618 abstract function getInputHTML( $value );
619
620 /**
621 * Override this function to add specific validation checks on the
622 * field input. Don't forget to call parent::validate() to ensure
623 * that the user-defined callback mValidationCallback is still run
624 * @param $value String the value the field was submitted with
625 * @param $alldata $all the data collected from the form
626 * @return Mixed Bool true on success, or String error to display.
627 */
628 function validate( $value, $alldata ) {
629 if ( isset( $this->mValidationCallback ) ) {
630 return call_user_func( $this->mValidationCallback, $value, $alldata );
631 }
632
633 return true;
634 }
635
636 function filter( $value, $alldata ) {
637 if( isset( $this->mFilterCallback ) ) {
638 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
639 }
640
641 return $value;
642 }
643
644 /**
645 * Should this field have a label, or is there no input element with the
646 * appropriate id for the label to point to?
647 *
648 * @return bool True to output a label, false to suppress
649 */
650 protected function needsLabel() {
651 return true;
652 }
653
654 /**
655 * Get the value that this input has been set to from a posted form,
656 * or the input's default value if it has not been set.
657 * @param $request WebRequest
658 * @return String the value
659 */
660 function loadDataFromRequest( $request ) {
661 if( $request->getCheck( $this->mName ) ) {
662 return $request->getText( $this->mName );
663 } else {
664 return $this->getDefault();
665 }
666 }
667
668 /**
669 * Initialise the object
670 * @param $params Associative Array. See HTMLForm doc for syntax.
671 */
672 function __construct( $params ) {
673 $this->mParams = $params;
674
675 # Generate the label from a message, if possible
676 if( isset( $params['label-message'] ) ) {
677 $msgInfo = $params['label-message'];
678
679 if ( is_array( $msgInfo ) ) {
680 $msg = array_shift( $msgInfo );
681 } else {
682 $msg = $msgInfo;
683 $msgInfo = array();
684 }
685
686 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
687 } elseif ( isset( $params['label'] ) ) {
688 $this->mLabel = $params['label'];
689 }
690
691 if ( isset( $params['name'] ) ) {
692 $name = $params['name'];
693 $validName = Sanitizer::escapeId( $name );
694 if( $name != $validName ) {
695 throw new MWException("Invalid name '$name' passed to " . __METHOD__ );
696 }
697 $this->mName = 'wp'.$name;
698 $this->mID = 'mw-input-'.$name;
699 }
700
701 if ( isset( $params['default'] ) ) {
702 $this->mDefault = $params['default'];
703 }
704
705 if ( isset( $params['id'] ) ) {
706 $id = $params['id'];
707 $validId = Sanitizer::escapeId( $id );
708 if( $id != $validId ) {
709 throw new MWException("Invalid id '$id' passed to " . __METHOD__ );
710 }
711 $this->mID = $id;
712 }
713
714 if ( isset( $params['validation-callback'] ) ) {
715 $this->mValidationCallback = $params['validation-callback'];
716 }
717
718 if ( isset( $params['filter-callback'] ) ) {
719 $this->mFilterCallback = $params['filter-callback'];
720 }
721 }
722
723 /**
724 * Get the complete table row for the input, including help text,
725 * labels, and whatever.
726 * @param $value String the value to set the input to.
727 * @return String complete HTML table row.
728 */
729 function getTableRow( $value ) {
730 # Check for invalid data.
731 global $wgRequest;
732
733 $errors = $this->validate( $value, $this->mParent->mFieldData );
734 if ( $errors === true || !$wgRequest->wasPosted() ) {
735 $errors = '';
736 } else {
737 $errors = Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
738 }
739
740 $html = '';
741
742 # Don't output a for= attribute for labels with no associated input.
743 # Kind of hacky here, possibly we don't want these to be <label>s at all.
744 $for = array();
745 if ( $this->needsLabel() ) {
746 $for['for'] = $this->mID;
747 }
748 $html .= Html::rawElement( 'td', array( 'class' => 'mw-label' ),
749 Html::rawElement( 'label', $for, $this->getLabel() )
750 );
751 $html .= Html::rawElement( 'td', array( 'class' => 'mw-input' ),
752 $this->getInputHTML( $value ) ."\n$errors" );
753
754 $fieldType = get_class( $this );
755
756 $html = Html::rawElement( 'tr', array( 'class' => "mw-htmlform-field-$fieldType" ),
757 $html ) . "\n";
758
759 $helptext = null;
760 if ( isset( $this->mParams['help-message'] ) ) {
761 $msg = $this->mParams['help-message'];
762 $helptext = wfMsgExt( $msg, 'parseinline' );
763 if ( wfEmptyMsg( $msg, $helptext ) ) {
764 # Never mind
765 $helptext = null;
766 }
767 } elseif ( isset( $this->mParams['help'] ) ) {
768 $helptext = $this->mParams['help'];
769 }
770
771 if ( !is_null( $helptext ) ) {
772 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
773 $helptext );
774 $row = Html::rawElement( 'tr', array(), $row );
775 $html .= "$row\n";
776 }
777
778 return $html;
779 }
780
781 function getLabel() {
782 return $this->mLabel;
783 }
784
785 function getDefault() {
786 if ( isset( $this->mDefault ) ) {
787 return $this->mDefault;
788 } else {
789 return null;
790 }
791 }
792
793 /**
794 * flatten an array of options to a single array, for instance,
795 * a set of <options> inside <optgroups>.
796 * @param $options Associative Array with values either Strings
797 * or Arrays
798 * @return Array flattened input
799 */
800 public static function flattenOptions( $options ) {
801 $flatOpts = array();
802
803 foreach( $options as $key => $value ) {
804 if ( is_array( $value ) ) {
805 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
806 } else {
807 $flatOpts[] = $value;
808 }
809 }
810
811 return $flatOpts;
812 }
813 }
814
815 class HTMLTextField extends HTMLFormField {
816
817 function getSize() {
818 return isset( $this->mParams['size'] )
819 ? $this->mParams['size']
820 : 45;
821 }
822
823 function getInputHTML( $value ) {
824 global $wgHtml5;
825 $attribs = array(
826 'id' => $this->mID,
827 'name' => $this->mName,
828 'size' => $this->getSize(),
829 'value' => $value,
830 );
831
832 if ( isset( $this->mParams['maxlength'] ) ) {
833 $attribs['maxlength'] = $this->mParams['maxlength'];
834 }
835
836 if ( !empty( $this->mParams['disabled'] ) ) {
837 $attribs['disabled'] = 'disabled';
838 }
839
840 if ( $wgHtml5 ) {
841 # TODO: Enforce pattern, step, required, readonly on the server
842 # side as well
843 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
844 'placeholder' ) as $param ) {
845 if ( isset( $this->mParams[$param] ) ) {
846 $attribs[$param] = $this->mParams[$param];
847 }
848 }
849 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' )
850 as $param ) {
851 if ( isset( $this->mParams[$param] ) ) {
852 $attribs[$param] = '';
853 }
854 }
855 }
856
857 # Implement tiny differences between some field variants
858 # here, rather than creating a new class for each one which
859 # is essentially just a clone of this one.
860 if ( isset( $this->mParams['type'] ) ) {
861 # Options that apply only to HTML5
862 if( $wgHtml5 ){
863 switch ( $this->mParams['type'] ) {
864 case 'email':
865 $attribs['type'] = 'email';
866 break;
867 case 'int':
868 $attribs['type'] = 'number';
869 break;
870 case 'float':
871 $attribs['type'] = 'number';
872 $attribs['step'] = 'any';
873 break;
874 }
875 }
876 # Options that apply to HTML4 as well
877 switch( $this->mParams['type'] ){
878 case 'password':
879 $attribs['type'] = 'password';
880 break;
881 }
882 }
883
884 return Html::element( 'input', $attribs );
885 }
886 }
887
888 /**
889 * A field that will contain a numeric value
890 */
891 class HTMLFloatField extends HTMLTextField {
892
893 function getSize() {
894 return isset( $this->mParams['size'] )
895 ? $this->mParams['size']
896 : 20;
897 }
898
899 function validate( $value, $alldata ) {
900 $p = parent::validate( $value, $alldata );
901
902 if ( $p !== true ) return $p;
903
904 if ( floatval( $value ) != $value ) {
905 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
906 }
907
908 $in_range = true;
909
910 # The "int" part of these message names is rather confusing.
911 # They make equal sense for all numbers.
912 if ( isset( $this->mParams['min'] ) ) {
913 $min = $this->mParams['min'];
914 if ( $min > $value )
915 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
916 }
917
918 if ( isset( $this->mParams['max'] ) ) {
919 $max = $this->mParams['max'];
920 if( $max < $value )
921 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
922 }
923
924 return true;
925 }
926 }
927
928 /**
929 * A field that must contain a number
930 */
931 class HTMLIntField extends HTMLFloatField {
932 function validate( $value, $alldata ) {
933 $p = parent::validate( $value, $alldata );
934
935 if ( $p !== true ) return $p;
936
937 if ( intval( $value ) != $value ) {
938 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
939 }
940
941 return true;
942 }
943 }
944
945 /**
946 * A checkbox field
947 */
948 class HTMLCheckField extends HTMLFormField {
949 function getInputHTML( $value ) {
950 if ( !empty( $this->mParams['invert'] ) )
951 $value = !$value;
952
953 $attr = array( 'id' => $this->mID );
954 if( !empty( $this->mParams['disabled'] ) ) {
955 $attr['disabled'] = 'disabled';
956 }
957
958 return Xml::check( $this->mName, $value, $attr ) . '&nbsp;' .
959 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
960 }
961
962 /**
963 * For a checkbox, the label goes on the right hand side, and is
964 * added in getInputHTML(), rather than HTMLFormField::getRow()
965 */
966 function getLabel() {
967 return '&nbsp;';
968 }
969
970 function loadDataFromRequest( $request ) {
971 $invert = false;
972 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
973 $invert = true;
974 }
975
976 // GetCheck won't work like we want for checks.
977 if( $request->getCheck( 'wpEditToken' ) ) {
978 // XOR has the following truth table, which is what we want
979 // INVERT VALUE | OUTPUT
980 // true true | false
981 // false true | true
982 // false false | false
983 // true false | true
984 return $request->getBool( $this->mName ) xor $invert;
985 } else {
986 return $this->getDefault();
987 }
988 }
989 }
990
991 /**
992 * A select dropdown field. Basically a wrapper for Xmlselect class
993 */
994 class HTMLSelectField extends HTMLFormField {
995
996 function validate( $value, $alldata ) {
997 $p = parent::validate( $value, $alldata );
998 if( $p !== true ) return $p;
999
1000 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1001 if ( in_array( $value, $validOptions ) )
1002 return true;
1003 else
1004 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1005 }
1006
1007 function getInputHTML( $value ) {
1008 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1009
1010 # If one of the options' 'name' is int(0), it is automatically selected.
1011 # because PHP sucks and things int(0) == 'some string'.
1012 # Working around this by forcing all of them to strings.
1013 $options = array_map( 'strval', $this->mParams['options'] );
1014
1015 if( !empty( $this->mParams['disabled'] ) ) {
1016 $select->setAttribute( 'disabled', 'disabled' );
1017 }
1018
1019 $select->addOptions( $options );
1020
1021 return $select->getHTML();
1022 }
1023 }
1024
1025 /**
1026 * Select dropdown field, with an additional "other" textbox.
1027 */
1028 class HTMLSelectOrOtherField extends HTMLTextField {
1029 static $jsAdded = false;
1030
1031 function __construct( $params ) {
1032 if( !in_array( 'other', $params['options'], true ) ) {
1033 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1034 }
1035
1036 parent::__construct( $params );
1037 }
1038
1039 static function forceToStringRecursive( $array ) {
1040 if ( is_array($array) ) {
1041 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array);
1042 } else {
1043 return strval($array);
1044 }
1045 }
1046
1047 function getInputHTML( $value ) {
1048 $valInSelect = false;
1049
1050 if( $value !== false )
1051 $valInSelect = in_array( $value,
1052 HTMLFormField::flattenOptions( $this->mParams['options'] ) );
1053
1054 $selected = $valInSelect ? $value : 'other';
1055
1056 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1057
1058 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1059 $select->addOptions( $opts );
1060
1061 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1062
1063 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1064 if( !empty( $this->mParams['disabled'] ) ) {
1065 $select->setAttribute( 'disabled', 'disabled' );
1066 $tbAttribs['disabled'] = 'disabled';
1067 }
1068
1069 $select = $select->getHTML();
1070
1071 if ( isset( $this->mParams['maxlength'] ) ) {
1072 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1073 }
1074
1075 $textbox = Html::input( $this->mName . '-other',
1076 $valInSelect ? '' : $value,
1077 'text',
1078 $tbAttribs );
1079
1080 return "$select<br/>\n$textbox";
1081 }
1082
1083 function loadDataFromRequest( $request ) {
1084 if( $request->getCheck( $this->mName ) ) {
1085 $val = $request->getText( $this->mName );
1086
1087 if( $val == 'other' ) {
1088 $val = $request->getText( $this->mName . '-other' );
1089 }
1090
1091 return $val;
1092 } else {
1093 return $this->getDefault();
1094 }
1095 }
1096 }
1097
1098 /**
1099 * Multi-select field
1100 */
1101 class HTMLMultiSelectField extends HTMLFormField {
1102
1103 function validate( $value, $alldata ) {
1104 $p = parent::validate( $value, $alldata );
1105 if( $p !== true ) return $p;
1106
1107 if( !is_array( $value ) ) return false;
1108
1109 # If all options are valid, array_intersect of the valid options
1110 # and the provided options will return the provided options.
1111 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1112
1113 $validValues = array_intersect( $value, $validOptions );
1114 if ( count( $validValues ) == count( $value ) )
1115 return true;
1116 else
1117 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1118 }
1119
1120 function getInputHTML( $value ) {
1121 $html = $this->formatOptions( $this->mParams['options'], $value );
1122
1123 return $html;
1124 }
1125
1126 function formatOptions( $options, $value ) {
1127 $html = '';
1128
1129 $attribs = array();
1130 if ( !empty( $this->mParams['disabled'] ) ) {
1131 $attribs['disabled'] = 'disabled';
1132 }
1133
1134 foreach( $options as $label => $info ) {
1135 if( is_array( $info ) ) {
1136 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1137 $html .= $this->formatOptions( $info, $value );
1138 } else {
1139 $thisAttribs = array( 'id' => $this->mID . "-$info", 'value' => $info );
1140
1141 $checkbox = Xml::check( $this->mName . '[]', in_array( $info, $value ),
1142 $attribs + $thisAttribs );
1143 $checkbox .= '&nbsp;' . Html::rawElement( 'label', array( 'for' => $this->mID . "-$info" ), $label );
1144
1145 $html .= $checkbox . '<br />';
1146 }
1147 }
1148
1149 return $html;
1150 }
1151
1152 function loadDataFromRequest( $request ) {
1153 # won't work with getCheck
1154 if( $request->getCheck( 'wpEditToken' ) ) {
1155 $arr = $request->getArray( $this->mName );
1156
1157 if( !$arr )
1158 $arr = array();
1159
1160 return $arr;
1161 } else {
1162 return $this->getDefault();
1163 }
1164 }
1165
1166 function getDefault() {
1167 if ( isset( $this->mDefault ) ) {
1168 return $this->mDefault;
1169 } else {
1170 return array();
1171 }
1172 }
1173
1174 protected function needsLabel() {
1175 return false;
1176 }
1177 }
1178
1179 /**
1180 * Radio checkbox fields.
1181 */
1182 class HTMLRadioField extends HTMLFormField {
1183 function validate( $value, $alldata ) {
1184 $p = parent::validate( $value, $alldata );
1185 if( $p !== true ) return $p;
1186
1187 if( !is_string( $value ) && !is_int( $value ) )
1188 return false;
1189
1190 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1191
1192 if ( in_array( $value, $validOptions ) )
1193 return true;
1194 else
1195 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1196 }
1197
1198 /**
1199 * This returns a block of all the radio options, in one cell.
1200 * @see includes/HTMLFormField#getInputHTML()
1201 */
1202 function getInputHTML( $value ) {
1203 $html = $this->formatOptions( $this->mParams['options'], $value );
1204
1205 return $html;
1206 }
1207
1208 function formatOptions( $options, $value ) {
1209 $html = '';
1210
1211 $attribs = array();
1212 if ( !empty( $this->mParams['disabled'] ) ) {
1213 $attribs['disabled'] = 'disabled';
1214 }
1215
1216 # TODO: should this produce an unordered list perhaps?
1217 foreach( $options as $label => $info ) {
1218 if( is_array( $info ) ) {
1219 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1220 $html .= $this->formatOptions( $info, $value );
1221 } else {
1222 $id = Sanitizer::escapeId( $this->mID . "-$info" );
1223 $html .= Xml::radio( $this->mName, $info, $info == $value,
1224 $attribs + array( 'id' => $id ) );
1225 $html .= '&nbsp;' .
1226 Html::rawElement( 'label', array( 'for' => $id ), $label );
1227
1228 $html .= "<br/>\n";
1229 }
1230 }
1231
1232 return $html;
1233 }
1234
1235 protected function needsLabel() {
1236 return false;
1237 }
1238 }
1239
1240 /**
1241 * An information field (text blob), not a proper input.
1242 */
1243 class HTMLInfoField extends HTMLFormField {
1244 function __construct( $info ) {
1245 $info['nodata'] = true;
1246
1247 parent::__construct( $info );
1248 }
1249
1250 function getInputHTML( $value ) {
1251 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
1252 }
1253
1254 function getTableRow( $value ) {
1255 if ( !empty( $this->mParams['rawrow'] ) ) {
1256 return $value;
1257 }
1258
1259 return parent::getTableRow( $value );
1260 }
1261
1262 protected function needsLabel() {
1263 return false;
1264 }
1265 }
1266
1267 class HTMLHiddenField extends HTMLFormField {
1268
1269 public function getTableRow( $value ){
1270 $this->mParent->addHiddenField(
1271 $this->mParams['name'],
1272 $this->mParams['default']
1273 );
1274 return '';
1275 }
1276
1277 public function getInputHTML( $value ){ return ''; }
1278 }
1279
1280 class HTMLSubmitField extends HTMLFormField {
1281
1282 public function getTableRow( $value ){
1283 $this->mParent->addButton(
1284 $this->mParams['name'],
1285 $this->mParams['default'],
1286 isset($this->mParams['id']) ? $this->mParams['id'] : null
1287 );
1288 }
1289
1290 public function getInputHTML( $value ){ return ''; }
1291 }