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