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