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