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