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