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