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