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