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