Adds support to HTMLForm for rendering form fields wrapped in divs
[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 text for a message to use as a help text.
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 * Overwrites 'help-messages' and 'help'.
38 * 'help-messages' -- array of message key. As above, each item can
39 * be an array of msg key and then parameters.
40 * Overwrites 'help'.
41 * 'required' -- passed through to the object, indicating that it
42 * is a required field.
43 * 'size' -- the length of text fields
44 * 'filter-callback -- a function name to give you the chance to
45 * massage the inputted value before it's processed.
46 * @see HTMLForm::filter()
47 * 'validation-callback' -- a function name to give you the chance
48 * to impose extra validation on the field input.
49 * @see HTMLForm::validate()
50 * 'name' -- By default, the 'name' attribute of the input field
51 * is "wp{$fieldname}". If you want a different name
52 * (eg one without the "wp" prefix), specify it here and
53 * it will be used without modification.
54 *
55 * TODO: Document 'section' / 'subsection' stuff
56 */
57 class HTMLForm extends ContextSource {
58
59 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
60 static $typeMappings = array(
61 'text' => 'HTMLTextField',
62 'textarea' => 'HTMLTextAreaField',
63 'select' => 'HTMLSelectField',
64 'radio' => 'HTMLRadioField',
65 'multiselect' => 'HTMLMultiSelectField',
66 'check' => 'HTMLCheckField',
67 'toggle' => 'HTMLCheckField',
68 'int' => 'HTMLIntField',
69 'float' => 'HTMLFloatField',
70 'info' => 'HTMLInfoField',
71 'selectorother' => 'HTMLSelectOrOtherField',
72 'selectandother' => 'HTMLSelectAndOtherField',
73 'submit' => 'HTMLSubmitField',
74 'hidden' => 'HTMLHiddenField',
75 'edittools' => 'HTMLEditTools',
76
77 // HTMLTextField will output the correct type="" attribute automagically.
78 // There are about four zillion other HTML5 input types, like url, but
79 // we don't use those at the moment, so no point in adding all of them.
80 'email' => 'HTMLTextField',
81 'password' => 'HTMLTextField',
82 );
83
84 protected $mMessagePrefix;
85
86 /** @var HTMLFormField[] */
87 protected $mFlatFields;
88
89 protected $mFieldTree;
90 protected $mShowReset = false;
91 public $mFieldData;
92
93 protected $mSubmitCallback;
94 protected $mValidationErrorMessage;
95
96 protected $mPre = '';
97 protected $mHeader = '';
98 protected $mFooter = '';
99 protected $mSectionHeaders = array();
100 protected $mSectionFooters = array();
101 protected $mPost = '';
102 protected $mId;
103
104 protected $mSubmitID;
105 protected $mSubmitName;
106 protected $mSubmitText;
107 protected $mSubmitTooltip;
108
109 protected $mTitle;
110 protected $mMethod = 'post';
111
112 /**
113 * Form action URL. false means we will use the URL to set Title
114 * @since 1.19
115 * @var bool|string
116 */
117 protected $mAction = false;
118
119 protected $mUseMultipart = false;
120 protected $mHiddenFields = array();
121 protected $mButtons = array();
122
123 protected $mWrapperLegend = false;
124
125 /**
126 * If true, sections that contain both fields and subsections will
127 * render their subsections before their fields.
128 *
129 * Subclasses may set this to false to render subsections after fields
130 * instead.
131 */
132 protected $mSubSectionBeforeFields = true;
133
134 /**
135 * Format in which to display form. For viable options,
136 * @see $availableDisplayFormats
137 * @var String
138 */
139 protected $displayFormat = 'table';
140
141 /**
142 * Available formats in which to display the form
143 * @var Array
144 */
145 protected $availableDisplayFormats = array(
146 'table',
147 'div',
148 'raw',
149 );
150
151 /**
152 * Build a new HTMLForm from an array of field attributes
153 * @param $descriptor Array of Field constructs, as described above
154 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
155 * Obviates the need to call $form->setTitle()
156 * @param $messagePrefix String a prefix to go in front of default messages
157 */
158 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
159 if ( $context instanceof IContextSource ) {
160 $this->setContext( $context );
161 $this->mTitle = false; // We don't need them to set a title
162 $this->mMessagePrefix = $messagePrefix;
163 } else {
164 // B/C since 1.18
165 if ( is_string( $context ) && $messagePrefix === '' ) {
166 // it's actually $messagePrefix
167 $this->mMessagePrefix = $context;
168 }
169 }
170
171 // Expand out into a tree.
172 $loadedDescriptor = array();
173 $this->mFlatFields = array();
174
175 foreach ( $descriptor as $fieldname => $info ) {
176 $section = isset( $info['section'] )
177 ? $info['section']
178 : '';
179
180 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
181 $this->mUseMultipart = true;
182 }
183
184 $field = self::loadInputFromParameters( $fieldname, $info );
185 $field->mParent = $this;
186
187 $setSection =& $loadedDescriptor;
188 if ( $section ) {
189 $sectionParts = explode( '/', $section );
190
191 while ( count( $sectionParts ) ) {
192 $newName = array_shift( $sectionParts );
193
194 if ( !isset( $setSection[$newName] ) ) {
195 $setSection[$newName] = array();
196 }
197
198 $setSection =& $setSection[$newName];
199 }
200 }
201
202 $setSection[$fieldname] = $field;
203 $this->mFlatFields[$fieldname] = $field;
204 }
205
206 $this->mFieldTree = $loadedDescriptor;
207 }
208
209 /**
210 * Set format in which to display the form
211 * @param $format String the name of the format to use, must be one of
212 * $this->availableDisplayFormats
213 * @since 1.20
214 */
215 public function setDisplayFormat( $format ) {
216 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
217 throw new MWException ( 'Display format must be one of ' . print_r( $this->availableDisplayFormats, true ) );
218 }
219 $this->displayFormat = $format;
220 }
221
222 /**
223 * Getter for displayFormat
224 * @since 1.20
225 * @return String
226 */
227 public function getDisplayFormat() {
228 return $this->displayFormat;
229 }
230
231 /**
232 * Add the HTMLForm-specific JavaScript, if it hasn't been
233 * done already.
234 * @deprecated since 1.18 load modules with ResourceLoader instead
235 */
236 static function addJS() { wfDeprecated( __METHOD__, '1.18' ); }
237
238 /**
239 * Initialise a new Object for the field
240 * @param $fieldname string
241 * @param $descriptor string input Descriptor, as described above
242 * @return HTMLFormField subclass
243 */
244 static function loadInputFromParameters( $fieldname, $descriptor ) {
245 if ( isset( $descriptor['class'] ) ) {
246 $class = $descriptor['class'];
247 } elseif ( isset( $descriptor['type'] ) ) {
248 $class = self::$typeMappings[$descriptor['type']];
249 $descriptor['class'] = $class;
250 } else {
251 $class = null;
252 }
253
254 if ( !$class ) {
255 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
256 }
257
258 $descriptor['fieldname'] = $fieldname;
259
260 # TODO
261 # This will throw a fatal error whenever someone try to use
262 # 'class' to feed a CSS class instead of 'cssclass'. Would be
263 # great to avoid the fatal error and show a nice error.
264 $obj = new $class( $descriptor );
265
266 return $obj;
267 }
268
269 /**
270 * Prepare form for submission
271 */
272 function prepareForm() {
273 # Check if we have the info we need
274 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
275 throw new MWException( "You must call setTitle() on an HTMLForm" );
276 }
277
278 # Load data from the request.
279 $this->loadData();
280 }
281
282 /**
283 * Try submitting, with edit token check first
284 * @return Status|boolean
285 */
286 function tryAuthorizedSubmit() {
287 $result = false;
288
289 $submit = false;
290 if ( $this->getMethod() != 'post' ) {
291 $submit = true; // no session check needed
292 } elseif ( $this->getRequest()->wasPosted() ) {
293 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
294 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
295 // Session tokens for logged-out users have no security value.
296 // However, if the user gave one, check it in order to give a nice
297 // "session expired" error instead of "permission denied" or such.
298 $submit = $this->getUser()->matchEditToken( $editToken );
299 } else {
300 $submit = true;
301 }
302 }
303
304 if ( $submit ) {
305 $result = $this->trySubmit();
306 }
307
308 return $result;
309 }
310
311 /**
312 * The here's-one-I-made-earlier option: do the submission if
313 * posted, or display the form with or without funky validation
314 * errors
315 * @return Bool or Status whether submission was successful.
316 */
317 function show() {
318 $this->prepareForm();
319
320 $result = $this->tryAuthorizedSubmit();
321 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
322 return $result;
323 }
324
325 $this->displayForm( $result );
326 return false;
327 }
328
329 /**
330 * Validate all the fields, and call the submision callback
331 * function if everything is kosher.
332 * @return Mixed Bool true == Successful submission, Bool false
333 * == No submission attempted, anything else == Error to
334 * display.
335 */
336 function trySubmit() {
337 # Check for validation
338 foreach ( $this->mFlatFields as $fieldname => $field ) {
339 if ( !empty( $field->mParams['nodata'] ) ) {
340 continue;
341 }
342 if ( $field->validate(
343 $this->mFieldData[$fieldname],
344 $this->mFieldData )
345 !== true
346 ) {
347 return isset( $this->mValidationErrorMessage )
348 ? $this->mValidationErrorMessage
349 : array( 'htmlform-invalid-input' );
350 }
351 }
352
353 $callback = $this->mSubmitCallback;
354
355 $data = $this->filterDataForSubmit( $this->mFieldData );
356
357 $res = call_user_func( $callback, $data, $this );
358
359 return $res;
360 }
361
362 /**
363 * Set a callback to a function to do something with the form
364 * once it's been successfully validated.
365 * @param $cb String function name. The function will be passed
366 * the output from HTMLForm::filterDataForSubmit, and must
367 * return Bool true on success, Bool false if no submission
368 * was attempted, or String HTML output to display on error.
369 */
370 function setSubmitCallback( $cb ) {
371 $this->mSubmitCallback = $cb;
372 }
373
374 /**
375 * Set a message to display on a validation error.
376 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
377 * (so each entry can be either a String or Array)
378 */
379 function setValidationErrorMessage( $msg ) {
380 $this->mValidationErrorMessage = $msg;
381 }
382
383 /**
384 * Set the introductory message, overwriting any existing message.
385 * @param $msg String complete text of message to display
386 */
387 function setIntro( $msg ) {
388 $this->setPreText( $msg );
389 }
390
391 /**
392 * Set the introductory message, overwriting any existing message.
393 * @since 1.19
394 * @param $msg String complete text of message to display
395 */
396 function setPreText( $msg ) { $this->mPre = $msg; }
397
398 /**
399 * Add introductory text.
400 * @param $msg String complete text of message to display
401 */
402 function addPreText( $msg ) { $this->mPre .= $msg; }
403
404 /**
405 * Add header text, inside the form.
406 * @param $msg String complete text of message to display
407 * @param $section string The section to add the header to
408 */
409 function addHeaderText( $msg, $section = null ) {
410 if ( is_null( $section ) ) {
411 $this->mHeader .= $msg;
412 } else {
413 if ( !isset( $this->mSectionHeaders[$section] ) ) {
414 $this->mSectionHeaders[$section] = '';
415 }
416 $this->mSectionHeaders[$section] .= $msg;
417 }
418 }
419
420 /**
421 * Set header text, inside the form.
422 * @since 1.19
423 * @param $msg String complete text of message to display
424 * @param $section The section to add the header to
425 */
426 function setHeaderText( $msg, $section = null ) {
427 if ( is_null( $section ) ) {
428 $this->mHeader = $msg;
429 } else {
430 $this->mSectionHeaders[$section] = $msg;
431 }
432 }
433
434 /**
435 * Add footer text, inside the form.
436 * @param $msg String complete text of message to display
437 * @param $section string The section to add the footer text to
438 */
439 function addFooterText( $msg, $section = null ) {
440 if ( is_null( $section ) ) {
441 $this->mFooter .= $msg;
442 } else {
443 if ( !isset( $this->mSectionFooters[$section] ) ) {
444 $this->mSectionFooters[$section] = '';
445 }
446 $this->mSectionFooters[$section] .= $msg;
447 }
448 }
449
450 /**
451 * Set footer text, inside the form.
452 * @since 1.19
453 * @param $msg String complete text of message to display
454 * @param $section string The section to add the footer text to
455 */
456 function setFooterText( $msg, $section = null ) {
457 if ( is_null( $section ) ) {
458 $this->mFooter = $msg;
459 } else {
460 $this->mSectionFooters[$section] = $msg;
461 }
462 }
463
464 /**
465 * Add text to the end of the display.
466 * @param $msg String complete text of message to display
467 */
468 function addPostText( $msg ) { $this->mPost .= $msg; }
469
470 /**
471 * Set text at the end of the display.
472 * @param $msg String complete text of message to display
473 */
474 function setPostText( $msg ) { $this->mPost = $msg; }
475
476 /**
477 * Add a hidden field to the output
478 * @param $name String field name. This will be used exactly as entered
479 * @param $value String field value
480 * @param $attribs Array
481 */
482 public function addHiddenField( $name, $value, $attribs = array() ) {
483 $attribs += array( 'name' => $name );
484 $this->mHiddenFields[] = array( $value, $attribs );
485 }
486
487 public function addButton( $name, $value, $id = null, $attribs = null ) {
488 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
489 }
490
491 /**
492 * Display the form (sending to $wgOut), with an appropriate error
493 * message or stack of messages, and any validation errors, etc.
494 * @param $submitResult Mixed output from HTMLForm::trySubmit()
495 */
496 function displayForm( $submitResult ) {
497 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
498 }
499
500 /**
501 * Returns the raw HTML generated by the form
502 * @param $submitResult Mixed output from HTMLForm::trySubmit()
503 * @return string
504 */
505 function getHTML( $submitResult ) {
506 # For good measure (it is the default)
507 $this->getOutput()->preventClickjacking();
508 $this->getOutput()->addModules( 'mediawiki.htmlform' );
509
510 $html = ''
511 . $this->getErrors( $submitResult )
512 . $this->mHeader
513 . $this->getBody()
514 . $this->getHiddenFields()
515 . $this->getButtons()
516 . $this->mFooter
517 ;
518
519 $html = $this->wrapForm( $html );
520
521 return '' . $this->mPre . $html . $this->mPost;
522 }
523
524 /**
525 * Wrap the form innards in an actual <form> element
526 * @param $html String HTML contents to wrap.
527 * @return String wrapped HTML.
528 */
529 function wrapForm( $html ) {
530
531 # Include a <fieldset> wrapper for style, if requested.
532 if ( $this->mWrapperLegend !== false ) {
533 $html = Xml::fieldset( $this->mWrapperLegend, $html );
534 }
535 # Use multipart/form-data
536 $encType = $this->mUseMultipart
537 ? 'multipart/form-data'
538 : 'application/x-www-form-urlencoded';
539 # Attributes
540 $attribs = array(
541 'action' => $this->mAction === false ? $this->getTitle()->getFullURL() : $this->mAction,
542 'method' => $this->mMethod,
543 'class' => 'visualClear',
544 'enctype' => $encType,
545 );
546 if ( !empty( $this->mId ) ) {
547 $attribs['id'] = $this->mId;
548 }
549
550 return Html::rawElement( 'form', $attribs, $html );
551 }
552
553 /**
554 * Get the hidden fields that should go inside the form.
555 * @return String HTML.
556 */
557 function getHiddenFields() {
558 global $wgArticlePath;
559
560 $html = '';
561 if ( $this->getMethod() == 'post' ) {
562 $html .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
563 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
564 }
565
566 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
567 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
568 }
569
570 foreach ( $this->mHiddenFields as $data ) {
571 list( $value, $attribs ) = $data;
572 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
573 }
574
575 return $html;
576 }
577
578 /**
579 * Get the submit and (potentially) reset buttons.
580 * @return String HTML.
581 */
582 function getButtons() {
583 $html = '';
584 $attribs = array();
585
586 if ( isset( $this->mSubmitID ) ) {
587 $attribs['id'] = $this->mSubmitID;
588 }
589
590 if ( isset( $this->mSubmitName ) ) {
591 $attribs['name'] = $this->mSubmitName;
592 }
593
594 if ( isset( $this->mSubmitTooltip ) ) {
595 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
596 }
597
598 $attribs['class'] = 'mw-htmlform-submit';
599
600 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
601
602 if ( $this->mShowReset ) {
603 $html .= Html::element(
604 'input',
605 array(
606 'type' => 'reset',
607 'value' => wfMsg( 'htmlform-reset' )
608 )
609 ) . "\n";
610 }
611
612 foreach ( $this->mButtons as $button ) {
613 $attrs = array(
614 'type' => 'submit',
615 'name' => $button['name'],
616 'value' => $button['value']
617 );
618
619 if ( $button['attribs'] ) {
620 $attrs += $button['attribs'];
621 }
622
623 if ( isset( $button['id'] ) ) {
624 $attrs['id'] = $button['id'];
625 }
626
627 $html .= Html::element( 'input', $attrs );
628 }
629
630 return $html;
631 }
632
633 /**
634 * Get the whole body of the form.
635 * @return String
636 */
637 function getBody() {
638 return $this->displaySection( $this->mFieldTree );
639 }
640
641 /**
642 * Format and display an error message stack.
643 * @param $errors String|Array|Status
644 * @return String
645 */
646 function getErrors( $errors ) {
647 if ( $errors instanceof Status ) {
648 if ( $errors->isOK() ) {
649 $errorstr = '';
650 } else {
651 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
652 }
653 } elseif ( is_array( $errors ) ) {
654 $errorstr = $this->formatErrors( $errors );
655 } else {
656 $errorstr = $errors;
657 }
658
659 return $errorstr
660 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
661 : '';
662 }
663
664 /**
665 * Format a stack of error messages into a single HTML string
666 * @param $errors Array of message keys/values
667 * @return String HTML, a <ul> list of errors
668 */
669 public static function formatErrors( $errors ) {
670 $errorstr = '';
671
672 foreach ( $errors as $error ) {
673 if ( is_array( $error ) ) {
674 $msg = array_shift( $error );
675 } else {
676 $msg = $error;
677 $error = array();
678 }
679
680 $errorstr .= Html::rawElement(
681 'li',
682 array(),
683 wfMsgExt( $msg, array( 'parseinline' ), $error )
684 );
685 }
686
687 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
688
689 return $errorstr;
690 }
691
692 /**
693 * Set the text for the submit button
694 * @param $t String plaintext.
695 */
696 function setSubmitText( $t ) {
697 $this->mSubmitText = $t;
698 }
699
700 /**
701 * Set the text for the submit button to a message
702 * @since 1.19
703 * @param $msg String message key
704 */
705 public function setSubmitTextMsg( $msg ) {
706 return $this->setSubmitText( $this->msg( $msg )->text() );
707 }
708
709 /**
710 * Get the text for the submit button, either customised or a default.
711 * @return string
712 */
713 function getSubmitText() {
714 return $this->mSubmitText
715 ? $this->mSubmitText
716 : wfMsg( 'htmlform-submit' );
717 }
718
719 public function setSubmitName( $name ) {
720 $this->mSubmitName = $name;
721 }
722
723 public function setSubmitTooltip( $name ) {
724 $this->mSubmitTooltip = $name;
725 }
726
727 /**
728 * Set the id for the submit button.
729 * @param $t String.
730 * @todo FIXME: Integrity of $t is *not* validated
731 */
732 function setSubmitID( $t ) {
733 $this->mSubmitID = $t;
734 }
735
736 public function setId( $id ) {
737 $this->mId = $id;
738 }
739 /**
740 * Prompt the whole form to be wrapped in a <fieldset>, with
741 * this text as its <legend> element.
742 * @param $legend String HTML to go inside the <legend> element.
743 * Will be escaped
744 */
745 public function setWrapperLegend( $legend ) { $this->mWrapperLegend = $legend; }
746
747 /**
748 * Prompt the whole form to be wrapped in a <fieldset>, with
749 * this message as its <legend> element.
750 * @since 1.19
751 * @param $msg String message key
752 */
753 public function setWrapperLegendMsg( $msg ) {
754 return $this->setWrapperLegend( $this->msg( $msg )->escaped() );
755 }
756
757 /**
758 * Set the prefix for various default messages
759 * TODO: currently only used for the <fieldset> legend on forms
760 * with multiple sections; should be used elsewhre?
761 * @param $p String
762 */
763 function setMessagePrefix( $p ) {
764 $this->mMessagePrefix = $p;
765 }
766
767 /**
768 * Set the title for form submission
769 * @param $t Title of page the form is on/should be posted to
770 */
771 function setTitle( $t ) {
772 $this->mTitle = $t;
773 }
774
775 /**
776 * Get the title
777 * @return Title
778 */
779 function getTitle() {
780 return $this->mTitle === false
781 ? $this->getContext()->getTitle()
782 : $this->mTitle;
783 }
784
785 /**
786 * Set the method used to submit the form
787 * @param $method String
788 */
789 public function setMethod( $method = 'post' ) {
790 $this->mMethod = $method;
791 }
792
793 public function getMethod() {
794 return $this->mMethod;
795 }
796
797 /**
798 * TODO: Document
799 * @param $fields array[]|HTMLFormField[] array of fields (either arrays or objects)
800 * @param $sectionName string ID attribute of the <table> tag for this section, ignored if empty
801 * @param $fieldsetIDPrefix string ID prefix for the <fieldset> tag of each subsection, ignored if empty
802 * @return String
803 */
804 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '' ) {
805 $displayFormat = $this->getDisplayFormat();
806
807 $html = '';
808 $subsectionHtml = '';
809 $hasLabel = false;
810
811 $getFieldHtmlMethod = ( $displayFormat == 'table' ) ? 'getTableRow' : 'get' . ucfirst( $displayFormat );
812
813 foreach ( $fields as $key => $value ) {
814 if ( $value instanceof HTMLFormField ) {
815 $v = empty( $value->mParams['nodata'] )
816 ? $this->mFieldData[$key]
817 : $value->getDefault();
818 $html .= $value->$getFieldHtmlMethod( $v );
819
820 $labelValue = trim( $value->getLabel() );
821 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
822 $hasLabel = true;
823 }
824 } elseif ( is_array( $value ) ) {
825 $section = $this->displaySection( $value, $key );
826 $legend = $this->getLegend( $key );
827 if ( isset( $this->mSectionHeaders[$key] ) ) {
828 $section = $this->mSectionHeaders[$key] . $section;
829 }
830 if ( isset( $this->mSectionFooters[$key] ) ) {
831 $section .= $this->mSectionFooters[$key];
832 }
833 $attributes = array();
834 if ( $fieldsetIDPrefix ) {
835 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
836 }
837 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
838 }
839 }
840
841 if ( $displayFormat !== 'raw' ) {
842 $classes = array();
843
844 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
845 $classes[] = 'mw-htmlform-nolabel';
846 }
847
848 $attribs = array(
849 'class' => implode( ' ', $classes ),
850 );
851
852 if ( $sectionName ) {
853 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
854 }
855
856 if ( $displayFormat === 'table' ) {
857 $html = Html::rawElement( 'table', $attribs,
858 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
859 } elseif ( $displayFormat === 'div' ) {
860 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
861 }
862 }
863
864 if ( $this->mSubSectionBeforeFields ) {
865 return $subsectionHtml . "\n" . $html;
866 } else {
867 return $html . "\n" . $subsectionHtml;
868 }
869 }
870
871 /**
872 * Construct the form fields from the Descriptor array
873 */
874 function loadData() {
875 $fieldData = array();
876
877 foreach ( $this->mFlatFields as $fieldname => $field ) {
878 if ( !empty( $field->mParams['nodata'] ) ) {
879 continue;
880 } elseif ( !empty( $field->mParams['disabled'] ) ) {
881 $fieldData[$fieldname] = $field->getDefault();
882 } else {
883 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
884 }
885 }
886
887 # Filter data.
888 foreach ( $fieldData as $name => &$value ) {
889 $field = $this->mFlatFields[$name];
890 $value = $field->filter( $value, $this->mFlatFields );
891 }
892
893 $this->mFieldData = $fieldData;
894 }
895
896 /**
897 * Stop a reset button being shown for this form
898 * @param $suppressReset Bool set to false to re-enable the
899 * button again
900 */
901 function suppressReset( $suppressReset = true ) {
902 $this->mShowReset = !$suppressReset;
903 }
904
905 /**
906 * Overload this if you want to apply special filtration routines
907 * to the form as a whole, after it's submitted but before it's
908 * processed.
909 * @param $data
910 * @return
911 */
912 function filterDataForSubmit( $data ) {
913 return $data;
914 }
915
916 /**
917 * Get a string to go in the <legend> of a section fieldset. Override this if you
918 * want something more complicated
919 * @param $key String
920 * @return String
921 */
922 public function getLegend( $key ) {
923 return wfMsg( "{$this->mMessagePrefix}-$key" );
924 }
925
926 /**
927 * Set the value for the action attribute of the form.
928 * When set to false (which is the default state), the set title is used.
929 *
930 * @since 1.19
931 *
932 * @param string|bool $action
933 */
934 public function setAction( $action ) {
935 $this->mAction = $action;
936 }
937
938 }
939
940 /**
941 * The parent class to generate form fields. Any field type should
942 * be a subclass of this.
943 */
944 abstract class HTMLFormField {
945
946 protected $mValidationCallback;
947 protected $mFilterCallback;
948 protected $mName;
949 public $mParams;
950 protected $mLabel; # String label. Set on construction
951 protected $mID;
952 protected $mClass = '';
953 protected $mDefault;
954
955 /**
956 * @var HTMLForm
957 */
958 public $mParent;
959
960 /**
961 * This function must be implemented to return the HTML to generate
962 * the input object itself. It should not implement the surrounding
963 * table cells/rows, or labels/help messages.
964 * @param $value String the value to set the input to; eg a default
965 * text for a text input.
966 * @return String valid HTML.
967 */
968 abstract function getInputHTML( $value );
969
970 /**
971 * Override this function to add specific validation checks on the
972 * field input. Don't forget to call parent::validate() to ensure
973 * that the user-defined callback mValidationCallback is still run
974 * @param $value String the value the field was submitted with
975 * @param $alldata Array the data collected from the form
976 * @return Mixed Bool true on success, or String error to display.
977 */
978 function validate( $value, $alldata ) {
979 if ( isset( $this->mParams['required'] ) && $value === '' ) {
980 return wfMsgExt( 'htmlform-required', 'parseinline' );
981 }
982
983 if ( isset( $this->mValidationCallback ) ) {
984 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
985 }
986
987 return true;
988 }
989
990 function filter( $value, $alldata ) {
991 if ( isset( $this->mFilterCallback ) ) {
992 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
993 }
994
995 return $value;
996 }
997
998 /**
999 * Should this field have a label, or is there no input element with the
1000 * appropriate id for the label to point to?
1001 *
1002 * @return bool True to output a label, false to suppress
1003 */
1004 protected function needsLabel() {
1005 return true;
1006 }
1007
1008 /**
1009 * Get the value that this input has been set to from a posted form,
1010 * or the input's default value if it has not been set.
1011 * @param $request WebRequest
1012 * @return String the value
1013 */
1014 function loadDataFromRequest( $request ) {
1015 if ( $request->getCheck( $this->mName ) ) {
1016 return $request->getText( $this->mName );
1017 } else {
1018 return $this->getDefault();
1019 }
1020 }
1021
1022 /**
1023 * Initialise the object
1024 * @param $params array Associative Array. See HTMLForm doc for syntax.
1025 */
1026 function __construct( $params ) {
1027 $this->mParams = $params;
1028
1029 # Generate the label from a message, if possible
1030 if ( isset( $params['label-message'] ) ) {
1031 $msgInfo = $params['label-message'];
1032
1033 if ( is_array( $msgInfo ) ) {
1034 $msg = array_shift( $msgInfo );
1035 } else {
1036 $msg = $msgInfo;
1037 $msgInfo = array();
1038 }
1039
1040 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
1041 } elseif ( isset( $params['label'] ) ) {
1042 $this->mLabel = $params['label'];
1043 }
1044
1045 $this->mName = "wp{$params['fieldname']}";
1046 if ( isset( $params['name'] ) ) {
1047 $this->mName = $params['name'];
1048 }
1049
1050 $validName = Sanitizer::escapeId( $this->mName );
1051 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1052 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1053 }
1054
1055 $this->mID = "mw-input-{$this->mName}";
1056
1057 if ( isset( $params['default'] ) ) {
1058 $this->mDefault = $params['default'];
1059 }
1060
1061 if ( isset( $params['id'] ) ) {
1062 $id = $params['id'];
1063 $validId = Sanitizer::escapeId( $id );
1064
1065 if ( $id != $validId ) {
1066 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1067 }
1068
1069 $this->mID = $id;
1070 }
1071
1072 if ( isset( $params['cssclass'] ) ) {
1073 $this->mClass = $params['cssclass'];
1074 }
1075
1076 if ( isset( $params['validation-callback'] ) ) {
1077 $this->mValidationCallback = $params['validation-callback'];
1078 }
1079
1080 if ( isset( $params['filter-callback'] ) ) {
1081 $this->mFilterCallback = $params['filter-callback'];
1082 }
1083
1084 if ( isset( $params['flatlist'] ) ) {
1085 $this->mClass .= ' mw-htmlform-flatlist';
1086 }
1087 }
1088
1089 /**
1090 * Get the complete table row for the input, including help text,
1091 * labels, and whatever.
1092 * @param $value String the value to set the input to.
1093 * @return String complete HTML table row.
1094 */
1095 function getTableRow( $value ) {
1096 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1097 $inputHtml = $this->getInputHTML( $value );
1098 $fieldType = get_class( $this );
1099 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1100 $cellAttributes = array();
1101
1102 if ( !empty( $this->mParams['vertical-label'] ) ) {
1103 $cellAttributes['colspan'] = 2;
1104 $verticalLabel = true;
1105 } else {
1106 $verticalLabel = false;
1107 }
1108
1109 $label = $this->getLabelHtml( $cellAttributes );
1110
1111 $field = Html::rawElement(
1112 'td',
1113 array( 'class' => 'mw-input' ) + $cellAttributes,
1114 $inputHtml . "\n$errors"
1115 );
1116
1117 if ( $verticalLabel ) {
1118 $html = Html::rawElement( 'tr',
1119 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1120 $html .= Html::rawElement( 'tr',
1121 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1122 $field );
1123 } else {
1124 $html = Html::rawElement( 'tr',
1125 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1126 $label . $field );
1127 }
1128
1129 return $html . $helptext;
1130 }
1131
1132 /**
1133 * Get the complete div for the input, including help text,
1134 * labels, and whatever.
1135 * @since 1.20
1136 * @param $value String the value to set the input to.
1137 * @return String complete HTML table row.
1138 */
1139 public function getDiv( $value ) {
1140 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1141 $inputHtml = $this->getInputHTML( $value );
1142 $fieldType = get_class( $this );
1143 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1144 $cellAttributes = array();
1145 $label = $this->getLabelHtml( $cellAttributes );
1146
1147 $field = Html::rawElement(
1148 'div',
1149 array( 'class' => 'mw-input' ) + $cellAttributes,
1150 $inputHtml . "\n$errors"
1151 );
1152 $html = Html::rawElement( 'div',
1153 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1154 $label . $field );
1155 $html .= $helptext;
1156 return $html;
1157 }
1158
1159 /**
1160 * Get the complete raw fields for the input, including help text,
1161 * labels, and whatever.
1162 * @since 1.20
1163 * @param $value String the value to set the input to.
1164 * @return String complete HTML table row.
1165 */
1166 public function getRaw( $value ) {
1167 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1168 $inputHtml = $this->getInputHTML( $value );
1169 $fieldType = get_class( $this );
1170 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1171 $cellAttributes = array();
1172 $label = $this->getLabelHtml( $cellAttributes );
1173
1174 $html = "\n$errors";
1175 $html .= $label;
1176 $html .= $inputHtml;
1177 $html .= $helptext;
1178 return $html;
1179 }
1180
1181 /**
1182 * Generate help text HTML in table format
1183 * @since 1.20
1184 * @param $helptext String|null
1185 * @return String
1186 */
1187 public function getHelpTextHtmlTable( $helptext ) {
1188 if ( is_null( $helptext ) ) {
1189 return '';
1190 }
1191
1192 $row = Html::rawElement(
1193 'td',
1194 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1195 $helptext
1196 );
1197 $row = Html::rawElement( 'tr', array(), $row );
1198 return $row;
1199 }
1200
1201 /**
1202 * Generate help text HTML in div format
1203 * @since 1.20
1204 * @param $helptext String|null
1205 * @return String
1206 */
1207 public function getHelpTextHtmlDiv( $helptext ) {
1208 if ( is_null( $helptext ) ) {
1209 return '';
1210 }
1211
1212 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1213 return $div;
1214 }
1215
1216 /**
1217 * Generate help text HTML formatted for raw output
1218 * @since 1.20
1219 * @param $helptext String|null
1220 * @return String
1221 */
1222 public function getHelpTextHtmlRaw( $helptext ) {
1223 return $this->getHelpTextHtmlDiv( $helptext );
1224 }
1225
1226 /**
1227 * Determine the help text to display
1228 * @since 1.20
1229 * @return String
1230 */
1231 public function getHelpText() {
1232 $helptext = null;
1233
1234 if ( isset( $this->mParams['help-message'] ) ) {
1235 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1236 }
1237
1238 if ( isset( $this->mParams['help-messages'] ) ) {
1239 foreach ( $this->mParams['help-messages'] as $name ) {
1240 $helpMessage = (array)$name;
1241 $msg = wfMessage( array_shift( $helpMessage ), $helpMessage );
1242
1243 if ( $msg->exists() ) {
1244 if ( is_null( $helptext ) ) {
1245 $helptext = '';
1246 } else {
1247 $helptext .= wfMessage( 'word-separator' )->escaped(); // some space
1248 }
1249 $helptext .= $msg->parse(); // Append message
1250 }
1251 }
1252 }
1253 elseif ( isset( $this->mParams['help'] ) ) {
1254 $helptext = $this->mParams['help'];
1255 }
1256 return $helptext;
1257 }
1258
1259 /**
1260 * Determine form errors to display and their classes
1261 * @since 1.20
1262 * @param $value String the value of the input
1263 * @return Array
1264 */
1265 public function getErrorsAndErrorClass( $value ) {
1266 $errors = $this->validate( $value, $this->mParent->mFieldData );
1267
1268 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1269 $errors = '';
1270 $errorClass = '';
1271 } else {
1272 $errors = self::formatErrors( $errors );
1273 $errorClass = 'mw-htmlform-invalid-input';
1274 }
1275 return array( $errors, $errorClass );
1276 }
1277
1278 function getLabel() {
1279 return $this->mLabel;
1280 }
1281
1282 function getLabelHtml( $cellAttributes = array() ) {
1283 # Don't output a for= attribute for labels with no associated input.
1284 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1285 $for = array();
1286
1287 if ( $this->needsLabel() ) {
1288 $for['for'] = $this->mID;
1289 }
1290
1291 $displayFormat = $this->mParent->getDisplayFormat();
1292 $labelElement = Html::rawElement( 'label', $for, $this->getLabel() );
1293
1294 if ( $displayFormat == 'table' ) {
1295 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1296 Html::rawElement( 'label', $for, $this->getLabel() )
1297 );
1298 } elseif ( $displayFormat == 'div' ) {
1299 return Html::rawElement( 'div', array( 'class' => 'mw-label' ) + $cellAttributes,
1300 Html::rawElement( 'label', $for, $this->getLabel() )
1301 );
1302 } else {
1303 return $labelElement;
1304 }
1305 }
1306
1307 function getDefault() {
1308 if ( isset( $this->mDefault ) ) {
1309 return $this->mDefault;
1310 } else {
1311 return null;
1312 }
1313 }
1314
1315 /**
1316 * Returns the attributes required for the tooltip and accesskey.
1317 *
1318 * @return array Attributes
1319 */
1320 public function getTooltipAndAccessKey() {
1321 if ( empty( $this->mParams['tooltip'] ) ) {
1322 return array();
1323 }
1324 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1325 }
1326
1327 /**
1328 * flatten an array of options to a single array, for instance,
1329 * a set of <options> inside <optgroups>.
1330 * @param $options array Associative Array with values either Strings
1331 * or Arrays
1332 * @return Array flattened input
1333 */
1334 public static function flattenOptions( $options ) {
1335 $flatOpts = array();
1336
1337 foreach ( $options as $value ) {
1338 if ( is_array( $value ) ) {
1339 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1340 } else {
1341 $flatOpts[] = $value;
1342 }
1343 }
1344
1345 return $flatOpts;
1346 }
1347
1348 /**
1349 * Formats one or more errors as accepted by field validation-callback.
1350 * @param $errors String|Message|Array of strings or Message instances
1351 * @return String html
1352 * @since 1.18
1353 */
1354 protected static function formatErrors( $errors ) {
1355 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1356 $errors = array_shift( $errors );
1357 }
1358
1359 if ( is_array( $errors ) ) {
1360 $lines = array();
1361 foreach ( $errors as $error ) {
1362 if ( $error instanceof Message ) {
1363 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1364 } else {
1365 $lines[] = Html::rawElement( 'li', array(), $error );
1366 }
1367 }
1368 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1369 } else {
1370 if ( $errors instanceof Message ) {
1371 $errors = $errors->parse();
1372 }
1373 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1374 }
1375 }
1376 }
1377
1378 class HTMLTextField extends HTMLFormField {
1379 function getSize() {
1380 return isset( $this->mParams['size'] )
1381 ? $this->mParams['size']
1382 : 45;
1383 }
1384
1385 function getInputHTML( $value ) {
1386 $attribs = array(
1387 'id' => $this->mID,
1388 'name' => $this->mName,
1389 'size' => $this->getSize(),
1390 'value' => $value,
1391 ) + $this->getTooltipAndAccessKey();
1392
1393 if ( $this->mClass !== '' ) {
1394 $attribs['class'] = $this->mClass;
1395 }
1396
1397 if ( isset( $this->mParams['maxlength'] ) ) {
1398 $attribs['maxlength'] = $this->mParams['maxlength'];
1399 }
1400
1401 if ( !empty( $this->mParams['disabled'] ) ) {
1402 $attribs['disabled'] = 'disabled';
1403 }
1404
1405 # TODO: Enforce pattern, step, required, readonly on the server side as
1406 # well
1407 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1408 'placeholder' ) as $param ) {
1409 if ( isset( $this->mParams[$param] ) ) {
1410 $attribs[$param] = $this->mParams[$param];
1411 }
1412 }
1413
1414 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1415 if ( isset( $this->mParams[$param] ) ) {
1416 $attribs[$param] = '';
1417 }
1418 }
1419
1420 # Implement tiny differences between some field variants
1421 # here, rather than creating a new class for each one which
1422 # is essentially just a clone of this one.
1423 if ( isset( $this->mParams['type'] ) ) {
1424 switch ( $this->mParams['type'] ) {
1425 case 'email':
1426 $attribs['type'] = 'email';
1427 break;
1428 case 'int':
1429 $attribs['type'] = 'number';
1430 break;
1431 case 'float':
1432 $attribs['type'] = 'number';
1433 $attribs['step'] = 'any';
1434 break;
1435 # Pass through
1436 case 'password':
1437 case 'file':
1438 $attribs['type'] = $this->mParams['type'];
1439 break;
1440 }
1441 }
1442
1443 return Html::element( 'input', $attribs );
1444 }
1445 }
1446 class HTMLTextAreaField extends HTMLFormField {
1447 function getCols() {
1448 return isset( $this->mParams['cols'] )
1449 ? $this->mParams['cols']
1450 : 80;
1451 }
1452
1453 function getRows() {
1454 return isset( $this->mParams['rows'] )
1455 ? $this->mParams['rows']
1456 : 25;
1457 }
1458
1459 function getInputHTML( $value ) {
1460 $attribs = array(
1461 'id' => $this->mID,
1462 'name' => $this->mName,
1463 'cols' => $this->getCols(),
1464 'rows' => $this->getRows(),
1465 ) + $this->getTooltipAndAccessKey();
1466
1467 if ( $this->mClass !== '' ) {
1468 $attribs['class'] = $this->mClass;
1469 }
1470
1471 if ( !empty( $this->mParams['disabled'] ) ) {
1472 $attribs['disabled'] = 'disabled';
1473 }
1474
1475 if ( !empty( $this->mParams['readonly'] ) ) {
1476 $attribs['readonly'] = 'readonly';
1477 }
1478
1479 if ( isset( $this->mParams['placeholder'] ) ) {
1480 $attribs['placeholder'] = $this->mParams['placeholder'];
1481 }
1482
1483 foreach ( array( 'required', 'autofocus' ) as $param ) {
1484 if ( isset( $this->mParams[$param] ) ) {
1485 $attribs[$param] = '';
1486 }
1487 }
1488
1489 return Html::element( 'textarea', $attribs, $value );
1490 }
1491 }
1492
1493 /**
1494 * A field that will contain a numeric value
1495 */
1496 class HTMLFloatField extends HTMLTextField {
1497 function getSize() {
1498 return isset( $this->mParams['size'] )
1499 ? $this->mParams['size']
1500 : 20;
1501 }
1502
1503 function validate( $value, $alldata ) {
1504 $p = parent::validate( $value, $alldata );
1505
1506 if ( $p !== true ) {
1507 return $p;
1508 }
1509
1510 $value = trim( $value );
1511
1512 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1513 # with the addition that a leading '+' sign is ok.
1514 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1515 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1516 }
1517
1518 # The "int" part of these message names is rather confusing.
1519 # They make equal sense for all numbers.
1520 if ( isset( $this->mParams['min'] ) ) {
1521 $min = $this->mParams['min'];
1522
1523 if ( $min > $value ) {
1524 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1525 }
1526 }
1527
1528 if ( isset( $this->mParams['max'] ) ) {
1529 $max = $this->mParams['max'];
1530
1531 if ( $max < $value ) {
1532 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1533 }
1534 }
1535
1536 return true;
1537 }
1538 }
1539
1540 /**
1541 * A field that must contain a number
1542 */
1543 class HTMLIntField extends HTMLFloatField {
1544 function validate( $value, $alldata ) {
1545 $p = parent::validate( $value, $alldata );
1546
1547 if ( $p !== true ) {
1548 return $p;
1549 }
1550
1551 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1552 # with the addition that a leading '+' sign is ok. Note that leading zeros
1553 # are fine, and will be left in the input, which is useful for things like
1554 # phone numbers when you know that they are integers (the HTML5 type=tel
1555 # input does not require its value to be numeric). If you want a tidier
1556 # value to, eg, save in the DB, clean it up with intval().
1557 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1558 ) {
1559 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1560 }
1561
1562 return true;
1563 }
1564 }
1565
1566 /**
1567 * A checkbox field
1568 */
1569 class HTMLCheckField extends HTMLFormField {
1570 function getInputHTML( $value ) {
1571 if ( !empty( $this->mParams['invert'] ) ) {
1572 $value = !$value;
1573 }
1574
1575 $attr = $this->getTooltipAndAccessKey();
1576 $attr['id'] = $this->mID;
1577
1578 if ( !empty( $this->mParams['disabled'] ) ) {
1579 $attr['disabled'] = 'disabled';
1580 }
1581
1582 if ( $this->mClass !== '' ) {
1583 $attr['class'] = $this->mClass;
1584 }
1585
1586 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1587 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1588 }
1589
1590 /**
1591 * For a checkbox, the label goes on the right hand side, and is
1592 * added in getInputHTML(), rather than HTMLFormField::getRow()
1593 * @return String
1594 */
1595 function getLabel() {
1596 return '&#160;';
1597 }
1598
1599 /**
1600 * @param $request WebRequest
1601 * @return String
1602 */
1603 function loadDataFromRequest( $request ) {
1604 $invert = false;
1605 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1606 $invert = true;
1607 }
1608
1609 // GetCheck won't work like we want for checks.
1610 // Fetch the value in either one of the two following case:
1611 // - we have a valid token (form got posted or GET forged by the user)
1612 // - checkbox name has a value (false or true), ie is not null
1613 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1614 // XOR has the following truth table, which is what we want
1615 // INVERT VALUE | OUTPUT
1616 // true true | false
1617 // false true | true
1618 // false false | false
1619 // true false | true
1620 return $request->getBool( $this->mName ) xor $invert;
1621 } else {
1622 return $this->getDefault();
1623 }
1624 }
1625 }
1626
1627 /**
1628 * A select dropdown field. Basically a wrapper for Xmlselect class
1629 */
1630 class HTMLSelectField extends HTMLFormField {
1631 function validate( $value, $alldata ) {
1632 $p = parent::validate( $value, $alldata );
1633
1634 if ( $p !== true ) {
1635 return $p;
1636 }
1637
1638 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1639
1640 if ( in_array( $value, $validOptions ) )
1641 return true;
1642 else
1643 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1644 }
1645
1646 function getInputHTML( $value ) {
1647 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1648
1649 # If one of the options' 'name' is int(0), it is automatically selected.
1650 # because PHP sucks and thinks int(0) == 'some string'.
1651 # Working around this by forcing all of them to strings.
1652 foreach ( $this->mParams['options'] as &$opt ) {
1653 if ( is_int( $opt ) ) {
1654 $opt = strval( $opt );
1655 }
1656 }
1657 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1658
1659 if ( !empty( $this->mParams['disabled'] ) ) {
1660 $select->setAttribute( 'disabled', 'disabled' );
1661 }
1662
1663 if ( $this->mClass !== '' ) {
1664 $select->setAttribute( 'class', $this->mClass );
1665 }
1666
1667 $select->addOptions( $this->mParams['options'] );
1668
1669 return $select->getHTML();
1670 }
1671 }
1672
1673 /**
1674 * Select dropdown field, with an additional "other" textbox.
1675 */
1676 class HTMLSelectOrOtherField extends HTMLTextField {
1677 static $jsAdded = false;
1678
1679 function __construct( $params ) {
1680 if ( !in_array( 'other', $params['options'], true ) ) {
1681 $msg = isset( $params['other'] ) ? $params['other'] : wfMsg( 'htmlform-selectorother-other' );
1682 $params['options'][$msg] = 'other';
1683 }
1684
1685 parent::__construct( $params );
1686 }
1687
1688 static function forceToStringRecursive( $array ) {
1689 if ( is_array( $array ) ) {
1690 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1691 } else {
1692 return strval( $array );
1693 }
1694 }
1695
1696 function getInputHTML( $value ) {
1697 $valInSelect = false;
1698
1699 if ( $value !== false ) {
1700 $valInSelect = in_array(
1701 $value,
1702 HTMLFormField::flattenOptions( $this->mParams['options'] )
1703 );
1704 }
1705
1706 $selected = $valInSelect ? $value : 'other';
1707
1708 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1709
1710 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1711 $select->addOptions( $opts );
1712
1713 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1714
1715 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1716
1717 if ( !empty( $this->mParams['disabled'] ) ) {
1718 $select->setAttribute( 'disabled', 'disabled' );
1719 $tbAttribs['disabled'] = 'disabled';
1720 }
1721
1722 $select = $select->getHTML();
1723
1724 if ( isset( $this->mParams['maxlength'] ) ) {
1725 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1726 }
1727
1728 if ( $this->mClass !== '' ) {
1729 $tbAttribs['class'] = $this->mClass;
1730 }
1731
1732 $textbox = Html::input(
1733 $this->mName . '-other',
1734 $valInSelect ? '' : $value,
1735 'text',
1736 $tbAttribs
1737 );
1738
1739 return "$select<br />\n$textbox";
1740 }
1741
1742 /**
1743 * @param $request WebRequest
1744 * @return String
1745 */
1746 function loadDataFromRequest( $request ) {
1747 if ( $request->getCheck( $this->mName ) ) {
1748 $val = $request->getText( $this->mName );
1749
1750 if ( $val == 'other' ) {
1751 $val = $request->getText( $this->mName . '-other' );
1752 }
1753
1754 return $val;
1755 } else {
1756 return $this->getDefault();
1757 }
1758 }
1759 }
1760
1761 /**
1762 * Multi-select field
1763 */
1764 class HTMLMultiSelectField extends HTMLFormField {
1765
1766 function validate( $value, $alldata ) {
1767 $p = parent::validate( $value, $alldata );
1768
1769 if ( $p !== true ) {
1770 return $p;
1771 }
1772
1773 if ( !is_array( $value ) ) {
1774 return false;
1775 }
1776
1777 # If all options are valid, array_intersect of the valid options
1778 # and the provided options will return the provided options.
1779 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1780
1781 $validValues = array_intersect( $value, $validOptions );
1782 if ( count( $validValues ) == count( $value ) ) {
1783 return true;
1784 } else {
1785 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1786 }
1787 }
1788
1789 function getInputHTML( $value ) {
1790 $html = $this->formatOptions( $this->mParams['options'], $value );
1791
1792 return $html;
1793 }
1794
1795 function formatOptions( $options, $value ) {
1796 $html = '';
1797
1798 $attribs = array();
1799
1800 if ( !empty( $this->mParams['disabled'] ) ) {
1801 $attribs['disabled'] = 'disabled';
1802 }
1803
1804 foreach ( $options as $label => $info ) {
1805 if ( is_array( $info ) ) {
1806 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1807 $html .= $this->formatOptions( $info, $value );
1808 } else {
1809 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1810
1811 $checkbox = Xml::check(
1812 $this->mName . '[]',
1813 in_array( $info, $value, true ),
1814 $attribs + $thisAttribs );
1815 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1816
1817 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
1818 }
1819 }
1820
1821 return $html;
1822 }
1823
1824 /**
1825 * @param $request WebRequest
1826 * @return String
1827 */
1828 function loadDataFromRequest( $request ) {
1829 if ( $this->mParent->getMethod() == 'post' ) {
1830 if ( $request->wasPosted() ) {
1831 # Checkboxes are just not added to the request arrays if they're not checked,
1832 # so it's perfectly possible for there not to be an entry at all
1833 return $request->getArray( $this->mName, array() );
1834 } else {
1835 # That's ok, the user has not yet submitted the form, so show the defaults
1836 return $this->getDefault();
1837 }
1838 } else {
1839 # This is the impossible case: if we look at $_GET and see no data for our
1840 # field, is it because the user has not yet submitted the form, or that they
1841 # have submitted it with all the options unchecked? We will have to assume the
1842 # latter, which basically means that you can't specify 'positive' defaults
1843 # for GET forms.
1844 # @todo FIXME...
1845 return $request->getArray( $this->mName, array() );
1846 }
1847 }
1848
1849 function getDefault() {
1850 if ( isset( $this->mDefault ) ) {
1851 return $this->mDefault;
1852 } else {
1853 return array();
1854 }
1855 }
1856
1857 protected function needsLabel() {
1858 return false;
1859 }
1860 }
1861
1862 /**
1863 * Double field with a dropdown list constructed from a system message in the format
1864 * * Optgroup header
1865 * ** <option value>
1866 * * New Optgroup header
1867 * Plus a text field underneath for an additional reason. The 'value' of the field is
1868 * ""<select>: <extra reason>"", or "<extra reason>" if nothing has been selected in the
1869 * select dropdown.
1870 * @todo FIXME: If made 'required', only the text field should be compulsory.
1871 */
1872 class HTMLSelectAndOtherField extends HTMLSelectField {
1873
1874 function __construct( $params ) {
1875 if ( array_key_exists( 'other', $params ) ) {
1876 } elseif ( array_key_exists( 'other-message', $params ) ) {
1877 $params['other'] = wfMessage( $params['other-message'] )->plain();
1878 } else {
1879 $params['other'] = null;
1880 }
1881
1882 if ( array_key_exists( 'options', $params ) ) {
1883 # Options array already specified
1884 } elseif ( array_key_exists( 'options-message', $params ) ) {
1885 # Generate options array from a system message
1886 $params['options'] = self::parseMessage(
1887 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
1888 $params['other']
1889 );
1890 } else {
1891 # Sulk
1892 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
1893 }
1894 $this->mFlatOptions = self::flattenOptions( $params['options'] );
1895
1896 parent::__construct( $params );
1897 }
1898
1899 /**
1900 * Build a drop-down box from a textual list.
1901 * @param $string String message text
1902 * @param $otherName String name of "other reason" option
1903 * @return Array
1904 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
1905 */
1906 public static function parseMessage( $string, $otherName = null ) {
1907 if ( $otherName === null ) {
1908 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
1909 }
1910
1911 $optgroup = false;
1912 $options = array( $otherName => 'other' );
1913
1914 foreach ( explode( "\n", $string ) as $option ) {
1915 $value = trim( $option );
1916 if ( $value == '' ) {
1917 continue;
1918 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
1919 # A new group is starting...
1920 $value = trim( substr( $value, 1 ) );
1921 $optgroup = $value;
1922 } elseif ( substr( $value, 0, 2 ) == '**' ) {
1923 # groupmember
1924 $opt = trim( substr( $value, 2 ) );
1925 if ( $optgroup === false ) {
1926 $options[$opt] = $opt;
1927 } else {
1928 $options[$optgroup][$opt] = $opt;
1929 }
1930 } else {
1931 # groupless reason list
1932 $optgroup = false;
1933 $options[$option] = $option;
1934 }
1935 }
1936
1937 return $options;
1938 }
1939
1940 function getInputHTML( $value ) {
1941 $select = parent::getInputHTML( $value[1] );
1942
1943 $textAttribs = array(
1944 'id' => $this->mID . '-other',
1945 'size' => $this->getSize(),
1946 );
1947
1948 if ( $this->mClass !== '' ) {
1949 $textAttribs['class'] = $this->mClass;
1950 }
1951
1952 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
1953 if ( isset( $this->mParams[$param] ) ) {
1954 $textAttribs[$param] = '';
1955 }
1956 }
1957
1958 $textbox = Html::input(
1959 $this->mName . '-other',
1960 $value[2],
1961 'text',
1962 $textAttribs
1963 );
1964
1965 return "$select<br />\n$textbox";
1966 }
1967
1968 /**
1969 * @param $request WebRequest
1970 * @return Array( <overall message>, <select value>, <text field value> )
1971 */
1972 function loadDataFromRequest( $request ) {
1973 if ( $request->getCheck( $this->mName ) ) {
1974
1975 $list = $request->getText( $this->mName );
1976 $text = $request->getText( $this->mName . '-other' );
1977
1978 if ( $list == 'other' ) {
1979 $final = $text;
1980 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
1981 # User has spoofed the select form to give an option which wasn't
1982 # in the original offer. Sulk...
1983 $final = $text;
1984 } elseif ( $text == '' ) {
1985 $final = $list;
1986 } else {
1987 $final = $list . wfMsgForContent( 'colon-separator' ) . $text;
1988 }
1989
1990 } else {
1991 $final = $this->getDefault();
1992
1993 $list = 'other';
1994 $text = $final;
1995 foreach ( $this->mFlatOptions as $option ) {
1996 $match = $option . wfMsgForContent( 'colon-separator' );
1997 if ( strpos( $text, $match ) === 0 ) {
1998 $list = $option;
1999 $text = substr( $text, strlen( $match ) );
2000 break;
2001 }
2002 }
2003 }
2004 return array( $final, $list, $text );
2005 }
2006
2007 function getSize() {
2008 return isset( $this->mParams['size'] )
2009 ? $this->mParams['size']
2010 : 45;
2011 }
2012
2013 function validate( $value, $alldata ) {
2014 # HTMLSelectField forces $value to be one of the options in the select
2015 # field, which is not useful here. But we do want the validation further up
2016 # the chain
2017 $p = parent::validate( $value[1], $alldata );
2018
2019 if ( $p !== true ) {
2020 return $p;
2021 }
2022
2023 if ( isset( $this->mParams['required'] ) && $value[1] === '' ) {
2024 return wfMsgExt( 'htmlform-required', 'parseinline' );
2025 }
2026
2027 return true;
2028 }
2029 }
2030
2031 /**
2032 * Radio checkbox fields.
2033 */
2034 class HTMLRadioField extends HTMLFormField {
2035
2036
2037 function validate( $value, $alldata ) {
2038 $p = parent::validate( $value, $alldata );
2039
2040 if ( $p !== true ) {
2041 return $p;
2042 }
2043
2044 if ( !is_string( $value ) && !is_int( $value ) ) {
2045 return false;
2046 }
2047
2048 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2049
2050 if ( in_array( $value, $validOptions ) ) {
2051 return true;
2052 } else {
2053 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
2054 }
2055 }
2056
2057 /**
2058 * This returns a block of all the radio options, in one cell.
2059 * @see includes/HTMLFormField#getInputHTML()
2060 * @param $value String
2061 * @return String
2062 */
2063 function getInputHTML( $value ) {
2064 $html = $this->formatOptions( $this->mParams['options'], $value );
2065
2066 return $html;
2067 }
2068
2069 function formatOptions( $options, $value ) {
2070 $html = '';
2071
2072 $attribs = array();
2073 if ( !empty( $this->mParams['disabled'] ) ) {
2074 $attribs['disabled'] = 'disabled';
2075 }
2076
2077 # TODO: should this produce an unordered list perhaps?
2078 foreach ( $options as $label => $info ) {
2079 if ( is_array( $info ) ) {
2080 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2081 $html .= $this->formatOptions( $info, $value );
2082 } else {
2083 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2084 $radio = Xml::radio(
2085 $this->mName,
2086 $info,
2087 $info == $value,
2088 $attribs + array( 'id' => $id )
2089 );
2090 $radio .= '&#160;' .
2091 Html::rawElement( 'label', array( 'for' => $id ), $label );
2092
2093 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2094 }
2095 }
2096
2097 return $html;
2098 }
2099
2100 protected function needsLabel() {
2101 return false;
2102 }
2103 }
2104
2105 /**
2106 * An information field (text blob), not a proper input.
2107 */
2108 class HTMLInfoField extends HTMLFormField {
2109 public function __construct( $info ) {
2110 $info['nodata'] = true;
2111
2112 parent::__construct( $info );
2113 }
2114
2115 public function getInputHTML( $value ) {
2116 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2117 }
2118
2119 public function getTableRow( $value ) {
2120 if ( !empty( $this->mParams['rawrow'] ) ) {
2121 return $value;
2122 }
2123
2124 return parent::getTableRow( $value );
2125 }
2126
2127 /**
2128 * @since 1.20
2129 */
2130 public function getDiv( $value ) {
2131 if ( !empty( $this->mParams['rawrow'] ) ) {
2132 return $value;
2133 }
2134
2135 return parent::getDiv( $value );
2136 }
2137
2138 /**
2139 * @since 1.20
2140 */
2141 public function getRaw( $value ) {
2142 if ( !empty( $this->mParams['rawrow'] ) ) {
2143 return $value;
2144 }
2145
2146 return parent::getRaw( $value );
2147 }
2148
2149 protected function needsLabel() {
2150 return false;
2151 }
2152 }
2153
2154 class HTMLHiddenField extends HTMLFormField {
2155 public function __construct( $params ) {
2156 parent::__construct( $params );
2157
2158 # Per HTML5 spec, hidden fields cannot be 'required'
2159 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2160 unset( $this->mParams['required'] );
2161 }
2162
2163 public function getTableRow( $value ) {
2164 $params = array();
2165 if ( $this->mID ) {
2166 $params['id'] = $this->mID;
2167 }
2168
2169 $this->mParent->addHiddenField(
2170 $this->mName,
2171 $this->mDefault,
2172 $params
2173 );
2174
2175 return '';
2176 }
2177
2178 /**
2179 * @since 1.20
2180 */
2181 public function getDiv( $value ) {
2182 return $this->getTableRow( $value );
2183 }
2184
2185 /**
2186 * @since 1.20
2187 */
2188 public function getRaw( $value ) {
2189 return $this->getTableRow( $value );
2190 }
2191
2192 public function getInputHTML( $value ) { return ''; }
2193 }
2194
2195 /**
2196 * Add a submit button inline in the form (as opposed to
2197 * HTMLForm::addButton(), which will add it at the end).
2198 */
2199 class HTMLSubmitField extends HTMLFormField {
2200
2201 public function __construct( $info ) {
2202 $info['nodata'] = true;
2203 parent::__construct( $info );
2204 }
2205
2206 public function getInputHTML( $value ) {
2207 return Xml::submitButton(
2208 $value,
2209 array(
2210 'class' => 'mw-htmlform-submit ' . $this->mClass,
2211 'name' => $this->mName,
2212 'id' => $this->mID,
2213 )
2214 );
2215 }
2216
2217 protected function needsLabel() {
2218 return false;
2219 }
2220
2221 /**
2222 * Button cannot be invalid
2223 * @param $value String
2224 * @param $alldata Array
2225 * @return Bool
2226 */
2227 public function validate( $value, $alldata ) {
2228 return true;
2229 }
2230 }
2231
2232 class HTMLEditTools extends HTMLFormField {
2233 public function getInputHTML( $value ) {
2234 return '';
2235 }
2236
2237 public function getTableRow( $value ) {
2238 $msg = $this->formatMsg();
2239
2240 return '<tr><td></td><td class="mw-input">'
2241 . '<div class="mw-editTools">'
2242 . $msg->parseAsBlock()
2243 . "</div></td></tr>\n";
2244 }
2245
2246 /**
2247 * @since 1.20
2248 */
2249 public function getDiv( $value ) {
2250 $msg = $this->formatMsg();
2251 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2252 }
2253
2254 /**
2255 * @since 1.20
2256 */
2257 public function getRaw( $value ) {
2258 return $this->getDiv( $value );
2259 }
2260
2261 protected function formatMsg() {
2262 if ( empty( $this->mParams['message'] ) ) {
2263 $msg = wfMessage( 'edittools' );
2264 } else {
2265 $msg = wfMessage( $this->mParams['message'] );
2266 if ( $msg->isDisabled() ) {
2267 $msg = wfMessage( 'edittools' );
2268 }
2269 }
2270 $msg->inContentLanguage();
2271 return $msg;
2272 }
2273 }