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