Merge "Use max() for job count for sanity"
[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 * You can find extensive documentation on the www.mediawiki.org wiki:
38 * - http://www.mediawiki.org/wiki/HTMLForm
39 * - http://www.mediawiki.org/wiki/HTMLForm/tutorial
40 *
41 * The constructor input is an associative array of $fieldname => $info,
42 * where $info is an Associative Array with any of the following:
43 *
44 * 'class' -- the subclass of HTMLFormField that will be used
45 * to create the object. *NOT* the CSS class!
46 * 'type' -- roughly translates into the <select> type attribute.
47 * if 'class' is not specified, this is used as a map
48 * through HTMLForm::$typeMappings to get the class name.
49 * 'default' -- default value when the form is displayed
50 * 'id' -- HTML id attribute
51 * 'cssclass' -- CSS class
52 * 'options' -- varies according to the specific object.
53 * 'label-message' -- message key for a message to use as the label.
54 * can be an array of msg key and then parameters to
55 * the message.
56 * 'label' -- alternatively, a raw text message. Overridden by
57 * label-message
58 * 'help' -- message text for a message to use as a help text.
59 * 'help-message' -- message key for a message to use as a help text.
60 * can be an array of msg key and then parameters to
61 * the message.
62 * Overwrites 'help-messages' and 'help'.
63 * 'help-messages' -- array of message key. As above, each item can
64 * be an array of msg key and then parameters.
65 * Overwrites 'help'.
66 * 'required' -- passed through to the object, indicating that it
67 * is a required field.
68 * 'size' -- the length of text fields
69 * 'filter-callback -- a function name to give you the chance to
70 * massage the inputted value before it's processed.
71 * @see HTMLForm::filter()
72 * 'validation-callback' -- a function name to give you the chance
73 * to impose extra validation on the field input.
74 * @see HTMLForm::validate()
75 * 'name' -- By default, the 'name' attribute of the input field
76 * is "wp{$fieldname}". If you want a different name
77 * (eg one without the "wp" prefix), specify it here and
78 * it will be used without modification.
79 *
80 * Since 1.20, you can chain mutators to ease the form generation:
81 * @par Example:
82 * @code
83 * $form = new HTMLForm( $someFields );
84 * $form->setMethod( 'get' )
85 * ->setWrapperLegendMsg( 'message-key' )
86 * ->prepareForm()
87 * ->displayForm( '' );
88 * @endcode
89 * Note that you will have prepareForm and displayForm at the end. Other
90 * methods call done after that would simply not be part of the form :(
91 *
92 * TODO: Document 'section' / 'subsection' stuff
93 */
94 class HTMLForm extends ContextSource {
95
96 // A mapping of 'type' inputs onto standard HTMLFormField subclasses
97 public static $typeMappings = array(
98 'api' => 'HTMLApiField',
99 'text' => 'HTMLTextField',
100 'textarea' => 'HTMLTextAreaField',
101 'select' => 'HTMLSelectField',
102 'radio' => 'HTMLRadioField',
103 'multiselect' => 'HTMLMultiSelectField',
104 'check' => 'HTMLCheckField',
105 'toggle' => 'HTMLCheckField',
106 'int' => 'HTMLIntField',
107 'float' => 'HTMLFloatField',
108 'info' => 'HTMLInfoField',
109 'selectorother' => 'HTMLSelectOrOtherField',
110 'selectandother' => 'HTMLSelectAndOtherField',
111 'submit' => 'HTMLSubmitField',
112 'hidden' => 'HTMLHiddenField',
113 'edittools' => 'HTMLEditTools',
114 'checkmatrix' => 'HTMLCheckMatrix',
115
116 // HTMLTextField will output the correct type="" attribute automagically.
117 // There are about four zillion other HTML5 input types, like url, but
118 // we don't use those at the moment, so no point in adding all of them.
119 'email' => 'HTMLTextField',
120 'password' => 'HTMLTextField',
121 );
122
123 protected $mMessagePrefix;
124
125 /** @var HTMLFormField[] */
126 protected $mFlatFields;
127
128 protected $mFieldTree;
129 protected $mShowReset = false;
130 protected $mShowSubmit = true;
131 public $mFieldData;
132
133 protected $mSubmitCallback;
134 protected $mValidationErrorMessage;
135
136 protected $mPre = '';
137 protected $mHeader = '';
138 protected $mFooter = '';
139 protected $mSectionHeaders = array();
140 protected $mSectionFooters = array();
141 protected $mPost = '';
142 protected $mId;
143 protected $mTableId = '';
144
145 protected $mSubmitID;
146 protected $mSubmitName;
147 protected $mSubmitText;
148 protected $mSubmitTooltip;
149
150 protected $mTitle;
151 protected $mMethod = 'post';
152
153 /**
154 * Form action URL. false means we will use the URL to set Title
155 * @since 1.19
156 * @var bool|string
157 */
158 protected $mAction = false;
159
160 protected $mUseMultipart = false;
161 protected $mHiddenFields = array();
162 protected $mButtons = array();
163
164 protected $mWrapperLegend = false;
165
166 /**
167 * If true, sections that contain both fields and subsections will
168 * render their subsections before their fields.
169 *
170 * Subclasses may set this to false to render subsections after fields
171 * instead.
172 */
173 protected $mSubSectionBeforeFields = true;
174
175 /**
176 * Format in which to display form. For viable options,
177 * @see $availableDisplayFormats
178 * @var String
179 */
180 protected $displayFormat = 'table';
181
182 /**
183 * Available formats in which to display the form
184 * @var Array
185 */
186 protected $availableDisplayFormats = array(
187 'table',
188 'div',
189 'raw',
190 'vform',
191 );
192
193 /**
194 * Build a new HTMLForm from an array of field attributes
195 * @param array $descriptor of Field constructs, as described above
196 * @param $context IContextSource available since 1.18, will become compulsory in 1.18.
197 * Obviates the need to call $form->setTitle()
198 * @param string $messagePrefix a prefix to go in front of default messages
199 */
200 public function __construct( $descriptor, /*IContextSource*/ $context = null, $messagePrefix = '' ) {
201 if ( $context instanceof IContextSource ) {
202 $this->setContext( $context );
203 $this->mTitle = false; // We don't need them to set a title
204 $this->mMessagePrefix = $messagePrefix;
205 } elseif ( is_null( $context ) && $messagePrefix !== '' ) {
206 $this->mMessagePrefix = $messagePrefix;
207 } elseif ( is_string( $context ) && $messagePrefix === '' ) {
208 // B/C since 1.18
209 // it's actually $messagePrefix
210 $this->mMessagePrefix = $context;
211 }
212
213 // Expand out into a tree.
214 $loadedDescriptor = array();
215 $this->mFlatFields = array();
216
217 foreach ( $descriptor as $fieldname => $info ) {
218 $section = isset( $info['section'] )
219 ? $info['section']
220 : '';
221
222 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
223 $this->mUseMultipart = true;
224 }
225
226 $field = self::loadInputFromParameters( $fieldname, $info );
227 // FIXME During field's construct, the parent form isn't available!
228 // could add a 'parent' name-value to $info, could add a third parameter.
229 $field->mParent = $this;
230
231 // vform gets too much space if empty labels generate HTML.
232 if ( $this->isVForm() ) {
233 $field->setShowEmptyLabel( false );
234 }
235
236 $setSection =& $loadedDescriptor;
237 if ( $section ) {
238 $sectionParts = explode( '/', $section );
239
240 while ( count( $sectionParts ) ) {
241 $newName = array_shift( $sectionParts );
242
243 if ( !isset( $setSection[$newName] ) ) {
244 $setSection[$newName] = array();
245 }
246
247 $setSection =& $setSection[$newName];
248 }
249 }
250
251 $setSection[$fieldname] = $field;
252 $this->mFlatFields[$fieldname] = $field;
253 }
254
255 $this->mFieldTree = $loadedDescriptor;
256 }
257
258 /**
259 * Set format in which to display the form
260 * @param string $format the name of the format to use, must be one of
261 * $this->availableDisplayFormats
262 * @throws MWException
263 * @since 1.20
264 * @return HTMLForm $this for chaining calls (since 1.20)
265 */
266 public function setDisplayFormat( $format ) {
267 if ( !in_array( $format, $this->availableDisplayFormats ) ) {
268 throw new MWException( 'Display format must be one of ' . print_r( $this->availableDisplayFormats, true ) );
269 }
270 $this->displayFormat = $format;
271 return $this;
272 }
273
274 /**
275 * Getter for displayFormat
276 * @since 1.20
277 * @return String
278 */
279 public function getDisplayFormat() {
280 return $this->displayFormat;
281 }
282
283 /**
284 * Test if displayFormat is 'vform'
285 * @since 1.22
286 * @return Bool
287 */
288 public function isVForm() {
289 return $this->displayFormat === 'vform';
290 }
291
292 /**
293 * Add the HTMLForm-specific JavaScript, if it hasn't been
294 * done already.
295 * @deprecated since 1.18 load modules with ResourceLoader instead
296 */
297 static function addJS() {
298 wfDeprecated( __METHOD__, '1.18' );
299 }
300
301 /**
302 * Initialise a new Object for the field
303 * @param $fieldname string
304 * @param string $descriptor input Descriptor, as described above
305 * @throws MWException
306 * @return HTMLFormField subclass
307 */
308 static function loadInputFromParameters( $fieldname, $descriptor ) {
309 if ( isset( $descriptor['class'] ) ) {
310 $class = $descriptor['class'];
311 } elseif ( isset( $descriptor['type'] ) ) {
312 $class = self::$typeMappings[$descriptor['type']];
313 $descriptor['class'] = $class;
314 } else {
315 $class = null;
316 }
317
318 if ( !$class ) {
319 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
320 }
321
322 $descriptor['fieldname'] = $fieldname;
323
324 # TODO
325 # This will throw a fatal error whenever someone try to use
326 # 'class' to feed a CSS class instead of 'cssclass'. Would be
327 # great to avoid the fatal error and show a nice error.
328 $obj = new $class( $descriptor );
329
330 return $obj;
331 }
332
333 /**
334 * Prepare form for submission.
335 *
336 * @attention When doing method chaining, that should be the very last
337 * method call before displayForm().
338 *
339 * @throws MWException
340 * @return HTMLForm $this for chaining calls (since 1.20)
341 */
342 function prepareForm() {
343 # Check if we have the info we need
344 if ( !$this->mTitle instanceof Title && $this->mTitle !== false ) {
345 throw new MWException( "You must call setTitle() on an HTMLForm" );
346 }
347
348 # Load data from the request.
349 $this->loadData();
350 return $this;
351 }
352
353 /**
354 * Try submitting, with edit token check first
355 * @return Status|boolean
356 */
357 function tryAuthorizedSubmit() {
358 $result = false;
359
360 $submit = false;
361 if ( $this->getMethod() != 'post' ) {
362 $submit = true; // no session check needed
363 } elseif ( $this->getRequest()->wasPosted() ) {
364 $editToken = $this->getRequest()->getVal( 'wpEditToken' );
365 if ( $this->getUser()->isLoggedIn() || $editToken != null ) {
366 // Session tokens for logged-out users have no security value.
367 // However, if the user gave one, check it in order to give a nice
368 // "session expired" error instead of "permission denied" or such.
369 $submit = $this->getUser()->matchEditToken( $editToken );
370 } else {
371 $submit = true;
372 }
373 }
374
375 if ( $submit ) {
376 $result = $this->trySubmit();
377 }
378
379 return $result;
380 }
381
382 /**
383 * The here's-one-I-made-earlier option: do the submission if
384 * posted, or display the form with or without funky validation
385 * errors
386 * @return Bool or Status whether submission was successful.
387 */
388 function show() {
389 $this->prepareForm();
390
391 $result = $this->tryAuthorizedSubmit();
392 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ) {
393 return $result;
394 }
395
396 $this->displayForm( $result );
397 return false;
398 }
399
400 /**
401 * Validate all the fields, and call the submission callback
402 * function if everything is kosher.
403 * @throws MWException
404 * @return Mixed Bool true == Successful submission, Bool false
405 * == No submission attempted, anything else == Error to
406 * display.
407 */
408 function trySubmit() {
409 # Check for validation
410 foreach ( $this->mFlatFields as $fieldname => $field ) {
411 if ( !empty( $field->mParams['nodata'] ) ) {
412 continue;
413 }
414 if ( $field->validate(
415 $this->mFieldData[$fieldname],
416 $this->mFieldData )
417 !== true
418 ) {
419 return isset( $this->mValidationErrorMessage )
420 ? $this->mValidationErrorMessage
421 : array( 'htmlform-invalid-input' );
422 }
423 }
424
425 $callback = $this->mSubmitCallback;
426 if ( !is_callable( $callback ) ) {
427 throw new MWException( 'HTMLForm: no submit callback provided. Use setSubmitCallback() to set one.' );
428 }
429
430 $data = $this->filterDataForSubmit( $this->mFieldData );
431
432 $res = call_user_func( $callback, $data, $this );
433
434 return $res;
435 }
436
437 /**
438 * Set a callback to a function to do something with the form
439 * once it's been successfully validated.
440 * @param string $cb function name. The function will be passed
441 * the output from HTMLForm::filterDataForSubmit, and must
442 * return Bool true on success, Bool false if no submission
443 * was attempted, or String HTML output to display on error.
444 * @return HTMLForm $this for chaining calls (since 1.20)
445 */
446 function setSubmitCallback( $cb ) {
447 $this->mSubmitCallback = $cb;
448 return $this;
449 }
450
451 /**
452 * Set a message to display on a validation error.
453 * @param $msg Mixed String or Array of valid inputs to wfMessage()
454 * (so each entry can be either a String or Array)
455 * @return HTMLForm $this for chaining calls (since 1.20)
456 */
457 function setValidationErrorMessage( $msg ) {
458 $this->mValidationErrorMessage = $msg;
459 return $this;
460 }
461
462 /**
463 * Set the introductory message, overwriting any existing message.
464 * @param string $msg complete text of message to display
465 * @return HTMLForm $this for chaining calls (since 1.20)
466 */
467 function setIntro( $msg ) {
468 $this->setPreText( $msg );
469 return $this;
470 }
471
472 /**
473 * Set the introductory message, overwriting any existing message.
474 * @since 1.19
475 * @param string $msg complete text of message to display
476 * @return HTMLForm $this for chaining calls (since 1.20)
477 */
478 function setPreText( $msg ) {
479 $this->mPre = $msg;
480 return $this;
481 }
482
483 /**
484 * Add introductory text.
485 * @param string $msg complete text of message to display
486 * @return HTMLForm $this for chaining calls (since 1.20)
487 */
488 function addPreText( $msg ) {
489 $this->mPre .= $msg;
490 return $this;
491 }
492
493 /**
494 * Add header text, inside the form.
495 * @param string $msg complete text of message to display
496 * @param string $section The section to add the header to
497 * @return HTMLForm $this for chaining calls (since 1.20)
498 */
499 function addHeaderText( $msg, $section = null ) {
500 if ( is_null( $section ) ) {
501 $this->mHeader .= $msg;
502 } else {
503 if ( !isset( $this->mSectionHeaders[$section] ) ) {
504 $this->mSectionHeaders[$section] = '';
505 }
506 $this->mSectionHeaders[$section] .= $msg;
507 }
508 return $this;
509 }
510
511 /**
512 * Set header text, inside the form.
513 * @since 1.19
514 * @param string $msg complete text of message to display
515 * @param $section The section to add the header to
516 * @return HTMLForm $this for chaining calls (since 1.20)
517 */
518 function setHeaderText( $msg, $section = null ) {
519 if ( is_null( $section ) ) {
520 $this->mHeader = $msg;
521 } else {
522 $this->mSectionHeaders[$section] = $msg;
523 }
524 return $this;
525 }
526
527 /**
528 * Add footer text, inside the form.
529 * @param string $msg complete text of message to display
530 * @param string $section The section to add the footer text to
531 * @return HTMLForm $this for chaining calls (since 1.20)
532 */
533 function addFooterText( $msg, $section = null ) {
534 if ( is_null( $section ) ) {
535 $this->mFooter .= $msg;
536 } else {
537 if ( !isset( $this->mSectionFooters[$section] ) ) {
538 $this->mSectionFooters[$section] = '';
539 }
540 $this->mSectionFooters[$section] .= $msg;
541 }
542 return $this;
543 }
544
545 /**
546 * Set footer text, inside the form.
547 * @since 1.19
548 * @param string $msg complete text of message to display
549 * @param string $section The section to add the footer text to
550 * @return HTMLForm $this for chaining calls (since 1.20)
551 */
552 function setFooterText( $msg, $section = null ) {
553 if ( is_null( $section ) ) {
554 $this->mFooter = $msg;
555 } else {
556 $this->mSectionFooters[$section] = $msg;
557 }
558 return $this;
559 }
560
561 /**
562 * Add text to the end of the display.
563 * @param string $msg complete text of message to display
564 * @return HTMLForm $this for chaining calls (since 1.20)
565 */
566 function addPostText( $msg ) {
567 $this->mPost .= $msg;
568 return $this;
569 }
570
571 /**
572 * Set text at the end of the display.
573 * @param string $msg complete text of message to display
574 * @return HTMLForm $this for chaining calls (since 1.20)
575 */
576 function setPostText( $msg ) {
577 $this->mPost = $msg;
578 return $this;
579 }
580
581 /**
582 * Add a hidden field to the output
583 * @param string $name field name. This will be used exactly as entered
584 * @param string $value field value
585 * @param $attribs Array
586 * @return HTMLForm $this for chaining calls (since 1.20)
587 */
588 public function addHiddenField( $name, $value, $attribs = array() ) {
589 $attribs += array( 'name' => $name );
590 $this->mHiddenFields[] = array( $value, $attribs );
591 return $this;
592 }
593
594 /**
595 * Add an array of hidden fields to the output
596 *
597 * @since 1.22
598 * @param array $fields Associative array of fields to add;
599 * mapping names to their values
600 * @return HTMLForm $this for chaining calls
601 */
602 public function addHiddenFields( array $fields ) {
603 foreach ( $fields as $name => $value ) {
604 $this->mHiddenFields[] = array( $value, array( 'name' => $name ) );
605 }
606 return $this;
607 }
608
609 /**
610 * Add a button to the form
611 * @param string $name field name.
612 * @param string $value field value
613 * @param string $id DOM id for the button (default: null)
614 * @param $attribs Array
615 * @return HTMLForm $this for chaining calls (since 1.20)
616 */
617 public function addButton( $name, $value, $id = null, $attribs = null ) {
618 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
619 return $this;
620 }
621
622 /**
623 * Display the form (sending to the context's OutputPage object), with an
624 * appropriate error message or stack of messages, and any validation errors, etc.
625 *
626 * @attention You should call prepareForm() before calling this function.
627 * Moreover, when doing method chaining this should be the very last method
628 * call just after prepareForm().
629 *
630 * @param $submitResult Mixed output from HTMLForm::trySubmit()
631 * @return Nothing, should be last call
632 */
633 function displayForm( $submitResult ) {
634 $this->getOutput()->addHTML( $this->getHTML( $submitResult ) );
635 }
636
637 /**
638 * Returns the raw HTML generated by the form
639 * @param $submitResult Mixed output from HTMLForm::trySubmit()
640 * @return string
641 */
642 function getHTML( $submitResult ) {
643 # For good measure (it is the default)
644 $this->getOutput()->preventClickjacking();
645 $this->getOutput()->addModules( 'mediawiki.htmlform' );
646 if ( $this->isVForm() ) {
647 $this->getOutput()->addModuleStyles( 'mediawiki.ui' );
648 // TODO should vertical form set setWrapperLegend( false )
649 // to hide ugly fieldsets?
650 }
651
652 $html = ''
653 . $this->getErrors( $submitResult )
654 . $this->mHeader
655 . $this->getBody()
656 . $this->getHiddenFields()
657 . $this->getButtons()
658 . $this->mFooter
659 ;
660
661 $html = $this->wrapForm( $html );
662
663 return '' . $this->mPre . $html . $this->mPost;
664 }
665
666 /**
667 * Wrap the form innards in an actual "<form>" element
668 * @param string $html HTML contents to wrap.
669 * @return String wrapped HTML.
670 */
671 function wrapForm( $html ) {
672
673 # Include a <fieldset> wrapper for style, if requested.
674 if ( $this->mWrapperLegend !== false ) {
675 $html = Xml::fieldset( $this->mWrapperLegend, $html );
676 }
677 # Use multipart/form-data
678 $encType = $this->mUseMultipart
679 ? 'multipart/form-data'
680 : 'application/x-www-form-urlencoded';
681 # Attributes
682 $attribs = array(
683 'action' => $this->getAction(),
684 'method' => $this->getMethod(),
685 'class' => array( 'visualClear' ),
686 'enctype' => $encType,
687 );
688 if ( !empty( $this->mId ) ) {
689 $attribs['id'] = $this->mId;
690 }
691
692 if ( $this->isVForm() ) {
693 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
694 }
695 return Html::rawElement( 'form', $attribs, $html );
696 }
697
698 /**
699 * Get the hidden fields that should go inside the form.
700 * @return String HTML.
701 */
702 function getHiddenFields() {
703 global $wgArticlePath;
704
705 $html = '';
706 if ( $this->getMethod() == 'post' ) {
707 $html .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
708 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
709 }
710
711 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
712 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
713 }
714
715 foreach ( $this->mHiddenFields as $data ) {
716 list( $value, $attribs ) = $data;
717 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
718 }
719
720 return $html;
721 }
722
723 /**
724 * Get the submit and (potentially) reset buttons.
725 * @return String HTML.
726 */
727 function getButtons() {
728 $html = '<span class="mw-htmlform-submit-buttons">';
729
730 if ( $this->mShowSubmit ) {
731 $attribs = array();
732
733 if ( isset( $this->mSubmitID ) ) {
734 $attribs['id'] = $this->mSubmitID;
735 }
736
737 if ( isset( $this->mSubmitName ) ) {
738 $attribs['name'] = $this->mSubmitName;
739 }
740
741 if ( isset( $this->mSubmitTooltip ) ) {
742 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
743 }
744
745 $attribs['class'] = array( 'mw-htmlform-submit' );
746
747 if ( $this->isVForm() ) {
748 // mw-ui-block is necessary because the buttons aren't necessarily in an
749 // immediate child div of the vform.
750 array_push( $attribs['class'], 'mw-ui-button', 'mw-ui-big', 'mw-ui-primary', 'mw-ui-block' );
751 }
752
753 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
754
755 // Buttons are top-level form elements in table and div layouts,
756 // but vform wants all elements inside divs to get spaced-out block
757 // styling.
758 if ( $this->isVForm() ) {
759 $html = Html::rawElement( 'div', null, "\n$html\n" );
760 }
761 }
762
763 if ( $this->mShowReset ) {
764 $html .= Html::element(
765 'input',
766 array(
767 'type' => 'reset',
768 'value' => $this->msg( 'htmlform-reset' )->text()
769 )
770 ) . "\n";
771 }
772
773 foreach ( $this->mButtons as $button ) {
774 $attrs = array(
775 'type' => 'submit',
776 'name' => $button['name'],
777 'value' => $button['value']
778 );
779
780 if ( $button['attribs'] ) {
781 $attrs += $button['attribs'];
782 }
783
784 if ( isset( $button['id'] ) ) {
785 $attrs['id'] = $button['id'];
786 }
787
788 $html .= Html::element( 'input', $attrs );
789 }
790
791 $html .= '</span>';
792
793 return $html;
794 }
795
796 /**
797 * Get the whole body of the form.
798 * @return String
799 */
800 function getBody() {
801 return $this->displaySection( $this->mFieldTree, $this->mTableId );
802 }
803
804 /**
805 * Format and display an error message stack.
806 * @param $errors String|Array|Status
807 * @return String
808 */
809 function getErrors( $errors ) {
810 if ( $errors instanceof Status ) {
811 if ( $errors->isOK() ) {
812 $errorstr = '';
813 } else {
814 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
815 }
816 } elseif ( is_array( $errors ) ) {
817 $errorstr = $this->formatErrors( $errors );
818 } else {
819 $errorstr = $errors;
820 }
821
822 return $errorstr
823 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
824 : '';
825 }
826
827 /**
828 * Format a stack of error messages into a single HTML string
829 * @param array $errors of message keys/values
830 * @return String HTML, a "<ul>" list of errors
831 */
832 public static function formatErrors( $errors ) {
833 $errorstr = '';
834
835 foreach ( $errors as $error ) {
836 if ( is_array( $error ) ) {
837 $msg = array_shift( $error );
838 } else {
839 $msg = $error;
840 $error = array();
841 }
842
843 $errorstr .= Html::rawElement(
844 'li',
845 array(),
846 wfMessage( $msg, $error )->parse()
847 );
848 }
849
850 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
851
852 return $errorstr;
853 }
854
855 /**
856 * Set the text for the submit button
857 * @param string $t plaintext.
858 * @return HTMLForm $this for chaining calls (since 1.20)
859 */
860 function setSubmitText( $t ) {
861 $this->mSubmitText = $t;
862 return $this;
863 }
864
865 /**
866 * Set the text for the submit button to a message
867 * @since 1.19
868 * @param string $msg message key
869 * @return HTMLForm $this for chaining calls (since 1.20)
870 */
871 public function setSubmitTextMsg( $msg ) {
872 $this->setSubmitText( $this->msg( $msg )->text() );
873 return $this;
874 }
875
876 /**
877 * Get the text for the submit button, either customised or a default.
878 * @return string
879 */
880 function getSubmitText() {
881 return $this->mSubmitText
882 ? $this->mSubmitText
883 : $this->msg( 'htmlform-submit' )->text();
884 }
885
886 /**
887 * @param string $name Submit button name
888 * @return HTMLForm $this for chaining calls (since 1.20)
889 */
890 public function setSubmitName( $name ) {
891 $this->mSubmitName = $name;
892 return $this;
893 }
894
895 /**
896 * @param string $name Tooltip for the submit button
897 * @return HTMLForm $this for chaining calls (since 1.20)
898 */
899 public function setSubmitTooltip( $name ) {
900 $this->mSubmitTooltip = $name;
901 return $this;
902 }
903
904 /**
905 * Set the id for the submit button.
906 * @param $t String.
907 * @todo FIXME: Integrity of $t is *not* validated
908 * @return HTMLForm $this for chaining calls (since 1.20)
909 */
910 function setSubmitID( $t ) {
911 $this->mSubmitID = $t;
912 return $this;
913 }
914
915 /**
916 * Stop a default submit button being shown for this form. This implies that an
917 * alternate submit method must be provided manually.
918 *
919 * @since 1.22
920 *
921 * @param bool $suppressSubmit Set to false to re-enable the button again
922 *
923 * @return HTMLForm $this for chaining calls
924 */
925 function suppressDefaultSubmit( $suppressSubmit = true ) {
926 $this->mShowSubmit = !$suppressSubmit;
927 return $this;
928 }
929
930 /**
931 * Set the id of the \<table\> or outermost \<div\> element.
932 *
933 * @since 1.22
934 * @param string $id new value of the id attribute, or "" to remove
935 * @return HTMLForm $this for chaining calls
936 */
937 public function setTableId( $id ) {
938 $this->mTableId = $id;
939 return $this;
940 }
941
942 /**
943 * @param string $id DOM id for the form
944 * @return HTMLForm $this for chaining calls (since 1.20)
945 */
946 public function setId( $id ) {
947 $this->mId = $id;
948 return $this;
949 }
950
951 /**
952 * Prompt the whole form to be wrapped in a "<fieldset>", with
953 * this text as its "<legend>" element.
954 * @param string|false $legend HTML to go inside the "<legend>" element, or
955 * false for no <legend>
956 * Will be escaped
957 * @return HTMLForm $this for chaining calls (since 1.20)
958 */
959 public function setWrapperLegend( $legend ) {
960 $this->mWrapperLegend = $legend;
961 return $this;
962 }
963
964 /**
965 * Prompt the whole form to be wrapped in a "<fieldset>", with
966 * this message as its "<legend>" element.
967 * @since 1.19
968 * @param string $msg message key
969 * @return HTMLForm $this for chaining calls (since 1.20)
970 */
971 public function setWrapperLegendMsg( $msg ) {
972 $this->setWrapperLegend( $this->msg( $msg )->text() );
973 return $this;
974 }
975
976 /**
977 * Set the prefix for various default messages
978 * @todo currently only used for the "<fieldset>" legend on forms
979 * with multiple sections; should be used elsewhere?
980 * @param $p String
981 * @return HTMLForm $this for chaining calls (since 1.20)
982 */
983 function setMessagePrefix( $p ) {
984 $this->mMessagePrefix = $p;
985 return $this;
986 }
987
988 /**
989 * Set the title for form submission
990 * @param $t Title of page the form is on/should be posted to
991 * @return HTMLForm $this for chaining calls (since 1.20)
992 */
993 function setTitle( $t ) {
994 $this->mTitle = $t;
995 return $this;
996 }
997
998 /**
999 * Get the title
1000 * @return Title
1001 */
1002 function getTitle() {
1003 return $this->mTitle === false
1004 ? $this->getContext()->getTitle()
1005 : $this->mTitle;
1006 }
1007
1008 /**
1009 * Set the method used to submit the form
1010 * @param $method String
1011 * @return HTMLForm $this for chaining calls (since 1.20)
1012 */
1013 public function setMethod( $method = 'post' ) {
1014 $this->mMethod = $method;
1015 return $this;
1016 }
1017
1018 public function getMethod() {
1019 return $this->mMethod;
1020 }
1021
1022 /**
1023 * @todo Document
1024 * @param array[]|HTMLFormField[] $fields array of fields (either arrays or objects)
1025 * @param string $sectionName ID attribute of the "<table>" tag for this section, ignored if empty
1026 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
1027 * @param boolean &$hasUserVisibleFields Whether the section had user-visible fields
1028 * @return String
1029 */
1030 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '', &$hasUserVisibleFields = false ) {
1031 $displayFormat = $this->getDisplayFormat();
1032
1033 $html = '';
1034 $subsectionHtml = '';
1035 $hasLabel = false;
1036
1037 switch( $displayFormat ) {
1038 case 'table':
1039 $getFieldHtmlMethod = 'getTableRow';
1040 break;
1041 case 'vform':
1042 // Close enough to a div.
1043 $getFieldHtmlMethod = 'getDiv';
1044 break;
1045 default:
1046 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1047 }
1048
1049 foreach ( $fields as $key => $value ) {
1050 if ( $value instanceof HTMLFormField ) {
1051 $v = empty( $value->mParams['nodata'] )
1052 ? $this->mFieldData[$key]
1053 : $value->getDefault();
1054 $html .= $value->$getFieldHtmlMethod( $v );
1055
1056 $labelValue = trim( $value->getLabel() );
1057 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1058 $hasLabel = true;
1059 }
1060
1061 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1062 get_class( $value ) !== 'HTMLApiField' ) {
1063 $hasUserVisibleFields = true;
1064 }
1065 } elseif ( is_array( $value ) ) {
1066 $subsectionHasVisibleFields = false;
1067 $section = $this->displaySection( $value, "mw-htmlform-$key", "$fieldsetIDPrefix$key-", $subsectionHasVisibleFields );
1068 $legend = null;
1069
1070 if ( $subsectionHasVisibleFields === true ) {
1071 // Display the section with various niceties.
1072 $hasUserVisibleFields = true;
1073
1074 $legend = $this->getLegend( $key );
1075
1076 if ( isset( $this->mSectionHeaders[$key] ) ) {
1077 $section = $this->mSectionHeaders[$key] . $section;
1078 }
1079 if ( isset( $this->mSectionFooters[$key] ) ) {
1080 $section .= $this->mSectionFooters[$key];
1081 }
1082
1083 $attributes = array();
1084 if ( $fieldsetIDPrefix ) {
1085 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1086 }
1087 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1088 } else {
1089 // Just return the inputs, nothing fancy.
1090 $subsectionHtml .= $section;
1091 }
1092 }
1093 }
1094
1095 if ( $displayFormat !== 'raw' ) {
1096 $classes = array();
1097
1098 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1099 $classes[] = 'mw-htmlform-nolabel';
1100 }
1101
1102 $attribs = array(
1103 'class' => implode( ' ', $classes ),
1104 );
1105
1106 if ( $sectionName ) {
1107 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1108 }
1109
1110 if ( $displayFormat === 'table' ) {
1111 $html = Html::rawElement( 'table', $attribs,
1112 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1113 } elseif ( $displayFormat === 'div' || $displayFormat === 'vform' ) {
1114 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1115 }
1116 }
1117
1118 if ( $this->mSubSectionBeforeFields ) {
1119 return $subsectionHtml . "\n" . $html;
1120 } else {
1121 return $html . "\n" . $subsectionHtml;
1122 }
1123 }
1124
1125 /**
1126 * Construct the form fields from the Descriptor array
1127 */
1128 function loadData() {
1129 $fieldData = array();
1130
1131 foreach ( $this->mFlatFields as $fieldname => $field ) {
1132 if ( !empty( $field->mParams['nodata'] ) ) {
1133 continue;
1134 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1135 $fieldData[$fieldname] = $field->getDefault();
1136 } else {
1137 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1138 }
1139 }
1140
1141 # Filter data.
1142 foreach ( $fieldData as $name => &$value ) {
1143 $field = $this->mFlatFields[$name];
1144 $value = $field->filter( $value, $this->mFlatFields );
1145 }
1146
1147 $this->mFieldData = $fieldData;
1148 }
1149
1150 /**
1151 * Stop a reset button being shown for this form
1152 * @param bool $suppressReset set to false to re-enable the
1153 * button again
1154 * @return HTMLForm $this for chaining calls (since 1.20)
1155 */
1156 function suppressReset( $suppressReset = true ) {
1157 $this->mShowReset = !$suppressReset;
1158 return $this;
1159 }
1160
1161 /**
1162 * Overload this if you want to apply special filtration routines
1163 * to the form as a whole, after it's submitted but before it's
1164 * processed.
1165 * @param $data
1166 * @return
1167 */
1168 function filterDataForSubmit( $data ) {
1169 return $data;
1170 }
1171
1172 /**
1173 * Get a string to go in the "<legend>" of a section fieldset.
1174 * Override this if you want something more complicated.
1175 * @param $key String
1176 * @return String
1177 */
1178 public function getLegend( $key ) {
1179 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1180 }
1181
1182 /**
1183 * Set the value for the action attribute of the form.
1184 * When set to false (which is the default state), the set title is used.
1185 *
1186 * @since 1.19
1187 *
1188 * @param string|bool $action
1189 * @return HTMLForm $this for chaining calls (since 1.20)
1190 */
1191 public function setAction( $action ) {
1192 $this->mAction = $action;
1193 return $this;
1194 }
1195
1196 /**
1197 * Get the value for the action attribute of the form.
1198 *
1199 * @since 1.22
1200 *
1201 * @return string
1202 */
1203 public function getAction() {
1204 global $wgScript, $wgArticlePath;
1205
1206 // If an action is alredy provided, return it
1207 if ( $this->mAction !== false ) {
1208 return $this->mAction;
1209 }
1210
1211 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1212 // meaning that getLocalURL() would return something like "index.php?title=...".
1213 // As browser remove the query string before submitting GET forms,
1214 // it means that the title would be lost. In such case use $wgScript instead
1215 // and put title in an hidden field (see getHiddenFields()).
1216 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1217 return $wgScript;
1218 }
1219
1220 return $this->getTitle()->getLocalURL();
1221 }
1222 }
1223
1224 /**
1225 * The parent class to generate form fields. Any field type should
1226 * be a subclass of this.
1227 */
1228 abstract class HTMLFormField {
1229
1230 protected $mValidationCallback;
1231 protected $mFilterCallback;
1232 protected $mName;
1233 public $mParams;
1234 protected $mLabel; # String label. Set on construction
1235 protected $mID;
1236 protected $mClass = '';
1237 protected $mDefault;
1238
1239 /**
1240 * @var bool If true will generate an empty div element with no label
1241 * @since 1.22
1242 */
1243 protected $mShowEmptyLabels = true;
1244
1245 /**
1246 * @var HTMLForm
1247 */
1248 public $mParent;
1249
1250 /**
1251 * This function must be implemented to return the HTML to generate
1252 * the input object itself. It should not implement the surrounding
1253 * table cells/rows, or labels/help messages.
1254 * @param string $value the value to set the input to; eg a default
1255 * text for a text input.
1256 * @return String valid HTML.
1257 */
1258 abstract function getInputHTML( $value );
1259
1260 /**
1261 * Get a translated interface message
1262 *
1263 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
1264 * and wfMessage() otherwise.
1265 *
1266 * Parameters are the same as wfMessage().
1267 *
1268 * @return Message object
1269 */
1270 function msg() {
1271 $args = func_get_args();
1272
1273 if ( $this->mParent ) {
1274 $callback = array( $this->mParent, 'msg' );
1275 } else {
1276 $callback = 'wfMessage';
1277 }
1278
1279 return call_user_func_array( $callback, $args );
1280 }
1281
1282 /**
1283 * Override this function to add specific validation checks on the
1284 * field input. Don't forget to call parent::validate() to ensure
1285 * that the user-defined callback mValidationCallback is still run
1286 * @param string $value the value the field was submitted with
1287 * @param array $alldata the data collected from the form
1288 * @return Mixed Bool true on success, or String error to display.
1289 */
1290 function validate( $value, $alldata ) {
1291 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value === '' ) {
1292 return $this->msg( 'htmlform-required' )->parse();
1293 }
1294
1295 if ( isset( $this->mValidationCallback ) ) {
1296 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
1297 }
1298
1299 return true;
1300 }
1301
1302 function filter( $value, $alldata ) {
1303 if ( isset( $this->mFilterCallback ) ) {
1304 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
1305 }
1306
1307 return $value;
1308 }
1309
1310 /**
1311 * Should this field have a label, or is there no input element with the
1312 * appropriate id for the label to point to?
1313 *
1314 * @return bool True to output a label, false to suppress
1315 */
1316 protected function needsLabel() {
1317 return true;
1318 }
1319
1320 /**
1321 * Tell the field whether to generate a separate label element if its label
1322 * is blank.
1323 *
1324 * @since 1.22
1325 * @param bool $show Set to false to not generate a label.
1326 * @return void
1327 */
1328 public function setShowEmptyLabel( $show ) {
1329 $this->mShowEmptyLabels = $show;
1330 }
1331
1332 /**
1333 * Get the value that this input has been set to from a posted form,
1334 * or the input's default value if it has not been set.
1335 * @param $request WebRequest
1336 * @return String the value
1337 */
1338 function loadDataFromRequest( $request ) {
1339 if ( $request->getCheck( $this->mName ) ) {
1340 return $request->getText( $this->mName );
1341 } else {
1342 return $this->getDefault();
1343 }
1344 }
1345
1346 /**
1347 * Initialise the object
1348 * @param array $params Associative Array. See HTMLForm doc for syntax.
1349 *
1350 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
1351 * @throws MWException
1352 */
1353 function __construct( $params ) {
1354 $this->mParams = $params;
1355
1356 # Generate the label from a message, if possible
1357 if ( isset( $params['label-message'] ) ) {
1358 $msgInfo = $params['label-message'];
1359
1360 if ( is_array( $msgInfo ) ) {
1361 $msg = array_shift( $msgInfo );
1362 } else {
1363 $msg = $msgInfo;
1364 $msgInfo = array();
1365 }
1366
1367 $this->mLabel = wfMessage( $msg, $msgInfo )->parse();
1368 } elseif ( isset( $params['label'] ) ) {
1369 if ( $params['label'] === '&#160;' ) {
1370 // Apparently some things set &nbsp directly and in an odd format
1371 $this->mLabel = '&#160;';
1372 } else {
1373 $this->mLabel = htmlspecialchars( $params['label'] );
1374 }
1375 } elseif ( isset( $params['label-raw'] ) ) {
1376 $this->mLabel = $params['label-raw'];
1377 }
1378
1379 $this->mName = "wp{$params['fieldname']}";
1380 if ( isset( $params['name'] ) ) {
1381 $this->mName = $params['name'];
1382 }
1383
1384 $validName = Sanitizer::escapeId( $this->mName );
1385 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1386 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1387 }
1388
1389 $this->mID = "mw-input-{$this->mName}";
1390
1391 if ( isset( $params['default'] ) ) {
1392 $this->mDefault = $params['default'];
1393 }
1394
1395 if ( isset( $params['id'] ) ) {
1396 $id = $params['id'];
1397 $validId = Sanitizer::escapeId( $id );
1398
1399 if ( $id != $validId ) {
1400 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1401 }
1402
1403 $this->mID = $id;
1404 }
1405
1406 if ( isset( $params['cssclass'] ) ) {
1407 $this->mClass = $params['cssclass'];
1408 }
1409
1410 if ( isset( $params['validation-callback'] ) ) {
1411 $this->mValidationCallback = $params['validation-callback'];
1412 }
1413
1414 if ( isset( $params['filter-callback'] ) ) {
1415 $this->mFilterCallback = $params['filter-callback'];
1416 }
1417
1418 if ( isset( $params['flatlist'] ) ) {
1419 $this->mClass .= ' mw-htmlform-flatlist';
1420 }
1421
1422 if ( isset( $params['hidelabel'] ) ) {
1423 $this->mShowEmptyLabels = false;
1424 }
1425 }
1426
1427 /**
1428 * Get the complete table row for the input, including help text,
1429 * labels, and whatever.
1430 * @param string $value the value to set the input to.
1431 * @return String complete HTML table row.
1432 */
1433 function getTableRow( $value ) {
1434 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1435 $inputHtml = $this->getInputHTML( $value );
1436 $fieldType = get_class( $this );
1437 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1438 $cellAttributes = array();
1439
1440 if ( !empty( $this->mParams['vertical-label'] ) ) {
1441 $cellAttributes['colspan'] = 2;
1442 $verticalLabel = true;
1443 } else {
1444 $verticalLabel = false;
1445 }
1446
1447 $label = $this->getLabelHtml( $cellAttributes );
1448
1449 $field = Html::rawElement(
1450 'td',
1451 array( 'class' => 'mw-input' ) + $cellAttributes,
1452 $inputHtml . "\n$errors"
1453 );
1454
1455 if ( $verticalLabel ) {
1456 $html = Html::rawElement( 'tr',
1457 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1458 $html .= Html::rawElement( 'tr',
1459 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1460 $field );
1461 } else {
1462 $html = Html::rawElement( 'tr',
1463 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1464 $label . $field );
1465 }
1466
1467 return $html . $helptext;
1468 }
1469
1470 /**
1471 * Get the complete div for the input, including help text,
1472 * labels, and whatever.
1473 * @since 1.20
1474 * @param string $value the value to set the input to.
1475 * @return String complete HTML table row.
1476 */
1477 public function getDiv( $value ) {
1478 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1479 $inputHtml = $this->getInputHTML( $value );
1480 $fieldType = get_class( $this );
1481 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1482 $cellAttributes = array();
1483 $label = $this->getLabelHtml( $cellAttributes );
1484
1485 $outerDivClass = array(
1486 'mw-input',
1487 'mw-htmlform-nolabel' => ( $label === '' )
1488 );
1489
1490 $field = Html::rawElement(
1491 'div',
1492 array( 'class' => $outerDivClass ) + $cellAttributes,
1493 $inputHtml . "\n$errors"
1494 );
1495 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass, $errorClass );
1496 if ( $this->mParent->isVForm() ) {
1497 $divCssClasses[] = 'mw-ui-vform-div';
1498 }
1499 $html = Html::rawElement( 'div',
1500 array( 'class' => $divCssClasses ),
1501 $label . $field );
1502 $html .= $helptext;
1503 return $html;
1504 }
1505
1506 /**
1507 * Get the complete raw fields for the input, including help text,
1508 * labels, and whatever.
1509 * @since 1.20
1510 * @param string $value the value to set the input to.
1511 * @return String complete HTML table row.
1512 */
1513 public function getRaw( $value ) {
1514 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
1515 $inputHtml = $this->getInputHTML( $value );
1516 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1517 $cellAttributes = array();
1518 $label = $this->getLabelHtml( $cellAttributes );
1519
1520 $html = "\n$errors";
1521 $html .= $label;
1522 $html .= $inputHtml;
1523 $html .= $helptext;
1524 return $html;
1525 }
1526
1527 /**
1528 * Generate help text HTML in table format
1529 * @since 1.20
1530 * @param $helptext String|null
1531 * @return String
1532 */
1533 public function getHelpTextHtmlTable( $helptext ) {
1534 if ( is_null( $helptext ) ) {
1535 return '';
1536 }
1537
1538 $row = Html::rawElement(
1539 'td',
1540 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1541 $helptext
1542 );
1543 $row = Html::rawElement( 'tr', array(), $row );
1544 return $row;
1545 }
1546
1547 /**
1548 * Generate help text HTML in div format
1549 * @since 1.20
1550 * @param $helptext String|null
1551 * @return String
1552 */
1553 public function getHelpTextHtmlDiv( $helptext ) {
1554 if ( is_null( $helptext ) ) {
1555 return '';
1556 }
1557
1558 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1559 return $div;
1560 }
1561
1562 /**
1563 * Generate help text HTML formatted for raw output
1564 * @since 1.20
1565 * @param $helptext String|null
1566 * @return String
1567 */
1568 public function getHelpTextHtmlRaw( $helptext ) {
1569 return $this->getHelpTextHtmlDiv( $helptext );
1570 }
1571
1572 /**
1573 * Determine the help text to display
1574 * @since 1.20
1575 * @return String
1576 */
1577 public function getHelpText() {
1578 $helptext = null;
1579
1580 if ( isset( $this->mParams['help-message'] ) ) {
1581 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1582 }
1583
1584 if ( isset( $this->mParams['help-messages'] ) ) {
1585 foreach ( $this->mParams['help-messages'] as $name ) {
1586 $helpMessage = (array)$name;
1587 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1588
1589 if ( $msg->exists() ) {
1590 if ( is_null( $helptext ) ) {
1591 $helptext = '';
1592 } else {
1593 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1594 }
1595 $helptext .= $msg->parse(); // Append message
1596 }
1597 }
1598 }
1599 elseif ( isset( $this->mParams['help'] ) ) {
1600 $helptext = $this->mParams['help'];
1601 }
1602 return $helptext;
1603 }
1604
1605 /**
1606 * Determine form errors to display and their classes
1607 * @since 1.20
1608 * @param string $value the value of the input
1609 * @return Array
1610 */
1611 public function getErrorsAndErrorClass( $value ) {
1612 $errors = $this->validate( $value, $this->mParent->mFieldData );
1613
1614 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1615 $errors = '';
1616 $errorClass = '';
1617 } else {
1618 $errors = self::formatErrors( $errors );
1619 $errorClass = 'mw-htmlform-invalid-input';
1620 }
1621 return array( $errors, $errorClass );
1622 }
1623
1624 function getLabel() {
1625 return is_null( $this->mLabel ) ? '' : $this->mLabel;
1626 }
1627
1628 function getLabelHtml( $cellAttributes = array() ) {
1629 # Don't output a for= attribute for labels with no associated input.
1630 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1631 $for = array();
1632
1633 if ( $this->needsLabel() ) {
1634 $for['for'] = $this->mID;
1635 }
1636
1637 $labelValue = trim( $this->getLabel() );
1638 $hasLabel = false;
1639 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
1640 $hasLabel = true;
1641 }
1642
1643 $displayFormat = $this->mParent->getDisplayFormat();
1644 $html = '';
1645
1646 if ( $displayFormat === 'table' ) {
1647 $html = Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1648 Html::rawElement( 'label', $for, $labelValue )
1649 );
1650 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
1651 if ( $displayFormat === 'div' ) {
1652 $html = Html::rawElement(
1653 'div',
1654 array( 'class' => 'mw-label' ) + $cellAttributes,
1655 Html::rawElement( 'label', $for, $labelValue )
1656 );
1657 } else {
1658 $html = Html::rawElement( 'label', $for, $labelValue );
1659 }
1660 }
1661
1662 return $html;
1663 }
1664
1665 function getDefault() {
1666 if ( isset( $this->mDefault ) ) {
1667 return $this->mDefault;
1668 } else {
1669 return null;
1670 }
1671 }
1672
1673 /**
1674 * Returns the attributes required for the tooltip and accesskey.
1675 *
1676 * @return array Attributes
1677 */
1678 public function getTooltipAndAccessKey() {
1679 if ( empty( $this->mParams['tooltip'] ) ) {
1680 return array();
1681 }
1682 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1683 }
1684
1685 /**
1686 * flatten an array of options to a single array, for instance,
1687 * a set of "<options>" inside "<optgroups>".
1688 * @param array $options Associative Array with values either Strings
1689 * or Arrays
1690 * @return Array flattened input
1691 */
1692 public static function flattenOptions( $options ) {
1693 $flatOpts = array();
1694
1695 foreach ( $options as $value ) {
1696 if ( is_array( $value ) ) {
1697 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1698 } else {
1699 $flatOpts[] = $value;
1700 }
1701 }
1702
1703 return $flatOpts;
1704 }
1705
1706 /**
1707 * Formats one or more errors as accepted by field validation-callback.
1708 * @param $errors String|Message|Array of strings or Message instances
1709 * @return String html
1710 * @since 1.18
1711 */
1712 protected static function formatErrors( $errors ) {
1713 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1714 $errors = array_shift( $errors );
1715 }
1716
1717 if ( is_array( $errors ) ) {
1718 $lines = array();
1719 foreach ( $errors as $error ) {
1720 if ( $error instanceof Message ) {
1721 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1722 } else {
1723 $lines[] = Html::rawElement( 'li', array(), $error );
1724 }
1725 }
1726 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1727 } else {
1728 if ( $errors instanceof Message ) {
1729 $errors = $errors->parse();
1730 }
1731 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1732 }
1733 }
1734 }
1735
1736 class HTMLTextField extends HTMLFormField {
1737 function getSize() {
1738 return isset( $this->mParams['size'] )
1739 ? $this->mParams['size']
1740 : 45;
1741 }
1742
1743 function getInputHTML( $value ) {
1744 $attribs = array(
1745 'id' => $this->mID,
1746 'name' => $this->mName,
1747 'size' => $this->getSize(),
1748 'value' => $value,
1749 ) + $this->getTooltipAndAccessKey();
1750
1751 if ( $this->mClass !== '' ) {
1752 $attribs['class'] = $this->mClass;
1753 }
1754
1755 if ( !empty( $this->mParams['disabled'] ) ) {
1756 $attribs['disabled'] = 'disabled';
1757 }
1758
1759 # TODO: Enforce pattern, step, required, readonly on the server side as
1760 # well
1761 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1762 'placeholder', 'list', 'maxlength' );
1763 foreach ( $allowedParams as $param ) {
1764 if ( isset( $this->mParams[$param] ) ) {
1765 $attribs[$param] = $this->mParams[$param];
1766 }
1767 }
1768
1769 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1770 if ( isset( $this->mParams[$param] ) ) {
1771 $attribs[$param] = '';
1772 }
1773 }
1774
1775 # Implement tiny differences between some field variants
1776 # here, rather than creating a new class for each one which
1777 # is essentially just a clone of this one.
1778 if ( isset( $this->mParams['type'] ) ) {
1779 switch ( $this->mParams['type'] ) {
1780 case 'email':
1781 $attribs['type'] = 'email';
1782 break;
1783 case 'int':
1784 $attribs['type'] = 'number';
1785 break;
1786 case 'float':
1787 $attribs['type'] = 'number';
1788 $attribs['step'] = 'any';
1789 break;
1790 # Pass through
1791 case 'password':
1792 case 'file':
1793 $attribs['type'] = $this->mParams['type'];
1794 break;
1795 }
1796 }
1797
1798 return Html::element( 'input', $attribs );
1799 }
1800 }
1801 class HTMLTextAreaField extends HTMLFormField {
1802 const DEFAULT_COLS = 80;
1803 const DEFAULT_ROWS = 25;
1804
1805 function getCols() {
1806 return isset( $this->mParams['cols'] )
1807 ? $this->mParams['cols']
1808 : static::DEFAULT_COLS;
1809 }
1810
1811 function getRows() {
1812 return isset( $this->mParams['rows'] )
1813 ? $this->mParams['rows']
1814 : static::DEFAULT_ROWS;
1815 }
1816
1817 function getInputHTML( $value ) {
1818 $attribs = array(
1819 'id' => $this->mID,
1820 'name' => $this->mName,
1821 'cols' => $this->getCols(),
1822 'rows' => $this->getRows(),
1823 ) + $this->getTooltipAndAccessKey();
1824
1825 if ( $this->mClass !== '' ) {
1826 $attribs['class'] = $this->mClass;
1827 }
1828
1829 if ( !empty( $this->mParams['disabled'] ) ) {
1830 $attribs['disabled'] = 'disabled';
1831 }
1832
1833 if ( !empty( $this->mParams['readonly'] ) ) {
1834 $attribs['readonly'] = 'readonly';
1835 }
1836
1837 if ( isset( $this->mParams['placeholder'] ) ) {
1838 $attribs['placeholder'] = $this->mParams['placeholder'];
1839 }
1840
1841 foreach ( array( 'required', 'autofocus' ) as $param ) {
1842 if ( isset( $this->mParams[$param] ) ) {
1843 $attribs[$param] = '';
1844 }
1845 }
1846
1847 return Html::element( 'textarea', $attribs, $value );
1848 }
1849 }
1850
1851 /**
1852 * A field that will contain a numeric value
1853 */
1854 class HTMLFloatField extends HTMLTextField {
1855 function getSize() {
1856 return isset( $this->mParams['size'] )
1857 ? $this->mParams['size']
1858 : 20;
1859 }
1860
1861 function validate( $value, $alldata ) {
1862 $p = parent::validate( $value, $alldata );
1863
1864 if ( $p !== true ) {
1865 return $p;
1866 }
1867
1868 $value = trim( $value );
1869
1870 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1871 # with the addition that a leading '+' sign is ok.
1872 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1873 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1874 }
1875
1876 # The "int" part of these message names is rather confusing.
1877 # They make equal sense for all numbers.
1878 if ( isset( $this->mParams['min'] ) ) {
1879 $min = $this->mParams['min'];
1880
1881 if ( $min > $value ) {
1882 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1883 }
1884 }
1885
1886 if ( isset( $this->mParams['max'] ) ) {
1887 $max = $this->mParams['max'];
1888
1889 if ( $max < $value ) {
1890 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1891 }
1892 }
1893
1894 return true;
1895 }
1896 }
1897
1898 /**
1899 * A field that must contain a number
1900 */
1901 class HTMLIntField extends HTMLFloatField {
1902 function validate( $value, $alldata ) {
1903 $p = parent::validate( $value, $alldata );
1904
1905 if ( $p !== true ) {
1906 return $p;
1907 }
1908
1909 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1910 # with the addition that a leading '+' sign is ok. Note that leading zeros
1911 # are fine, and will be left in the input, which is useful for things like
1912 # phone numbers when you know that they are integers (the HTML5 type=tel
1913 # input does not require its value to be numeric). If you want a tidier
1914 # value to, eg, save in the DB, clean it up with intval().
1915 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1916 ) {
1917 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1918 }
1919
1920 return true;
1921 }
1922 }
1923
1924 /**
1925 * A checkbox field
1926 */
1927 class HTMLCheckField extends HTMLFormField {
1928 function getInputHTML( $value ) {
1929 if ( !empty( $this->mParams['invert'] ) ) {
1930 $value = !$value;
1931 }
1932
1933 $attr = $this->getTooltipAndAccessKey();
1934 $attr['id'] = $this->mID;
1935
1936 if ( !empty( $this->mParams['disabled'] ) ) {
1937 $attr['disabled'] = 'disabled';
1938 }
1939
1940 if ( $this->mClass !== '' ) {
1941 $attr['class'] = $this->mClass;
1942 }
1943
1944 if ( $this->mParent->isVForm() ) {
1945 // Nest checkbox inside label.
1946 return Html::rawElement(
1947 'label',
1948 array(
1949 'class' => 'mw-ui-checkbox-label'
1950 ),
1951 Xml::check(
1952 $this->mName,
1953 $value,
1954 $attr
1955 ) .
1956 // Html:rawElement doesn't escape contents.
1957 htmlspecialchars( $this->mLabel )
1958 );
1959 } else {
1960 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1961 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1962 }
1963 }
1964
1965 /**
1966 * For a checkbox, the label goes on the right hand side, and is
1967 * added in getInputHTML(), rather than HTMLFormField::getRow()
1968 * @return String
1969 */
1970 function getLabel() {
1971 return '&#160;';
1972 }
1973
1974 /**
1975 * checkboxes don't need a label.
1976 */
1977 protected function needsLabel() {
1978 return false;
1979 }
1980
1981 /**
1982 * @param $request WebRequest
1983 * @return String
1984 */
1985 function loadDataFromRequest( $request ) {
1986 $invert = false;
1987 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1988 $invert = true;
1989 }
1990
1991 // GetCheck won't work like we want for checks.
1992 // Fetch the value in either one of the two following case:
1993 // - we have a valid token (form got posted or GET forged by the user)
1994 // - checkbox name has a value (false or true), ie is not null
1995 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1996 // XOR has the following truth table, which is what we want
1997 // INVERT VALUE | OUTPUT
1998 // true true | false
1999 // false true | true
2000 // false false | false
2001 // true false | true
2002 return $request->getBool( $this->mName ) xor $invert;
2003 } else {
2004 return $this->getDefault();
2005 }
2006 }
2007 }
2008
2009 /**
2010 * A checkbox matrix
2011 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
2012 * options, uses an array of rows and an array of columns to dynamically
2013 * construct a matrix of options. The tags used to identify a particular cell
2014 * are of the form "columnName-rowName"
2015 *
2016 * Options:
2017 * - columns
2018 * - Required list of columns in the matrix.
2019 * - rows
2020 * - Required list of rows in the matrix.
2021 * - force-options-on
2022 * - Accepts array of column-row tags to be displayed as enabled but unavailable to change
2023 * - force-options-off
2024 * - Accepts array of column-row tags to be displayed as disabled but unavailable to change.
2025 * - tooltips
2026 * - Optional array mapping row label to tooltip content
2027 * - tooltip-class
2028 * - Optional CSS class used on tooltip container span. Defaults to mw-icon-question.
2029 */
2030 class HTMLCheckMatrix extends HTMLFormField implements HTMLNestedFilterable {
2031
2032 static private $requiredParams = array(
2033 // Required by underlying HTMLFormField
2034 'fieldname',
2035 // Required by HTMLCheckMatrix
2036 'rows', 'columns'
2037 );
2038
2039 public function __construct( $params ) {
2040 $missing = array_diff( self::$requiredParams, array_keys( $params ) );
2041 if ( $missing ) {
2042 throw new HTMLFormFieldRequiredOptionsException( $this, $missing );
2043 }
2044 parent::__construct( $params );
2045 }
2046
2047 function validate( $value, $alldata ) {
2048 $rows = $this->mParams['rows'];
2049 $columns = $this->mParams['columns'];
2050
2051 // Make sure user-defined validation callback is run
2052 $p = parent::validate( $value, $alldata );
2053 if ( $p !== true ) {
2054 return $p;
2055 }
2056
2057 // Make sure submitted value is an array
2058 if ( !is_array( $value ) ) {
2059 return false;
2060 }
2061
2062 // If all options are valid, array_intersect of the valid options
2063 // and the provided options will return the provided options.
2064 $validOptions = array();
2065 foreach ( $rows as $rowTag ) {
2066 foreach ( $columns as $columnTag ) {
2067 $validOptions[] = $columnTag . '-' . $rowTag;
2068 }
2069 }
2070 $validValues = array_intersect( $value, $validOptions );
2071 if ( count( $validValues ) == count( $value ) ) {
2072 return true;
2073 } else {
2074 return $this->msg( 'htmlform-select-badoption' )->parse();
2075 }
2076 }
2077
2078 /**
2079 * Build a table containing a matrix of checkbox options.
2080 * The value of each option is a combination of the row tag and column tag.
2081 * mParams['rows'] is an array with row labels as keys and row tags as values.
2082 * mParams['columns'] is an array with column labels as keys and column tags as values.
2083 * @param array $value of the options that should be checked
2084 * @return String
2085 */
2086 function getInputHTML( $value ) {
2087 $html = '';
2088 $tableContents = '';
2089 $attribs = array();
2090 $rows = $this->mParams['rows'];
2091 $columns = $this->mParams['columns'];
2092
2093 // If the disabled param is set, disable all the options
2094 if ( !empty( $this->mParams['disabled'] ) ) {
2095 $attribs['disabled'] = 'disabled';
2096 }
2097
2098 // Build the column headers
2099 $headerContents = Html::rawElement( 'td', array(), '&#160;' );
2100 foreach ( $columns as $columnLabel => $columnTag ) {
2101 $headerContents .= Html::rawElement( 'td', array(), $columnLabel );
2102 }
2103 $tableContents .= Html::rawElement( 'tr', array(), "\n$headerContents\n" );
2104
2105 $tooltipClass = 'mw-icon-question';
2106 if ( isset( $this->mParams['tooltip-class'] ) ) {
2107 $tooltipClass = $this->mParams['tooltip-class'];
2108 }
2109
2110 // Build the options matrix
2111 foreach ( $rows as $rowLabel => $rowTag ) {
2112 // Append tooltip if configured
2113 if ( isset( $this->mParams['tooltips'][$rowLabel] ) ) {
2114 $tooltipAttribs = array(
2115 'class' => "mw-htmlform-tooltip $tooltipClass",
2116 'title' => $this->mParams['tooltips'][$rowLabel],
2117 );
2118 $rowLabel .= ' ' . Html::element( 'span', $tooltipAttribs, '' );
2119 }
2120 $rowContents = Html::rawElement( 'td', array(), $rowLabel );
2121 foreach ( $columns as $columnTag ) {
2122 $thisTag = "$columnTag-$rowTag";
2123 // Construct the checkbox
2124 $thisAttribs = array(
2125 'id' => "{$this->mID}-$thisTag",
2126 'value' => $thisTag,
2127 );
2128 $checked = in_array( $thisTag, (array)$value, true );
2129 if ( $this->isTagForcedOff( $thisTag ) ) {
2130 $checked = false;
2131 $thisAttribs['disabled'] = 1;
2132 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2133 $checked = true;
2134 $thisAttribs['disabled'] = 1;
2135 }
2136 $rowContents .= Html::rawElement(
2137 'td',
2138 array(),
2139 Xml::check( "{$this->mName}[]", $checked, $attribs + $thisAttribs )
2140 );
2141 }
2142 $tableContents .= Html::rawElement( 'tr', array(), "\n$rowContents\n" );
2143 }
2144
2145 // Put it all in a table
2146 $html .= Html::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
2147 Html::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
2148
2149 return $html;
2150 }
2151
2152 protected function isTagForcedOff( $tag ) {
2153 return isset( $this->mParams['force-options-off'] )
2154 && in_array( $tag, $this->mParams['force-options-off'] );
2155 }
2156
2157 protected function isTagForcedOn( $tag ) {
2158 return isset( $this->mParams['force-options-on'] )
2159 && in_array( $tag, $this->mParams['force-options-on'] );
2160 }
2161
2162 /**
2163 * Get the complete table row for the input, including help text,
2164 * labels, and whatever.
2165 * We override this function since the label should always be on a separate
2166 * line above the options in the case of a checkbox matrix, i.e. it's always
2167 * a "vertical-label".
2168 * @param string $value the value to set the input to
2169 * @return String complete HTML table row
2170 */
2171 function getTableRow( $value ) {
2172 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
2173 $inputHtml = $this->getInputHTML( $value );
2174 $fieldType = get_class( $this );
2175 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
2176 $cellAttributes = array( 'colspan' => 2 );
2177
2178 $label = $this->getLabelHtml( $cellAttributes );
2179
2180 $field = Html::rawElement(
2181 'td',
2182 array( 'class' => 'mw-input' ) + $cellAttributes,
2183 $inputHtml . "\n$errors"
2184 );
2185
2186 $html = Html::rawElement( 'tr',
2187 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
2188 $html .= Html::rawElement( 'tr',
2189 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
2190 $field );
2191
2192 return $html . $helptext;
2193 }
2194
2195 /**
2196 * @param $request WebRequest
2197 * @return Array
2198 */
2199 function loadDataFromRequest( $request ) {
2200 if ( $this->mParent->getMethod() == 'post' ) {
2201 if ( $request->wasPosted() ) {
2202 // Checkboxes are not added to the request arrays if they're not checked,
2203 // so it's perfectly possible for there not to be an entry at all
2204 return $request->getArray( $this->mName, array() );
2205 } else {
2206 // That's ok, the user has not yet submitted the form, so show the defaults
2207 return $this->getDefault();
2208 }
2209 } else {
2210 // This is the impossible case: if we look at $_GET and see no data for our
2211 // field, is it because the user has not yet submitted the form, or that they
2212 // have submitted it with all the options unchecked. We will have to assume the
2213 // latter, which basically means that you can't specify 'positive' defaults
2214 // for GET forms.
2215 return $request->getArray( $this->mName, array() );
2216 }
2217 }
2218
2219 function getDefault() {
2220 if ( isset( $this->mDefault ) ) {
2221 return $this->mDefault;
2222 } else {
2223 return array();
2224 }
2225 }
2226
2227 function filterDataForSubmit( $data ) {
2228 $columns = HTMLFormField::flattenOptions( $this->mParams['columns'] );
2229 $rows = HTMLFormField::flattenOptions( $this->mParams['rows'] );
2230 $res = array();
2231 foreach ( $columns as $column ) {
2232 foreach ( $rows as $row ) {
2233 // Make sure option hasn't been forced
2234 $thisTag = "$column-$row";
2235 if ( $this->isTagForcedOff( $thisTag ) ) {
2236 $res[$thisTag] = false;
2237 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2238 $res[$thisTag] = true;
2239 } else {
2240 $res[$thisTag] = in_array( $thisTag, $data );
2241 }
2242 }
2243 }
2244
2245 return $res;
2246 }
2247 }
2248
2249 /**
2250 * A select dropdown field. Basically a wrapper for Xmlselect class
2251 */
2252 class HTMLSelectField extends HTMLFormField {
2253 function validate( $value, $alldata ) {
2254 $p = parent::validate( $value, $alldata );
2255
2256 if ( $p !== true ) {
2257 return $p;
2258 }
2259
2260 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2261
2262 if ( in_array( $value, $validOptions ) ) {
2263 return true;
2264 } else {
2265 return $this->msg( 'htmlform-select-badoption' )->parse();
2266 }
2267 }
2268
2269 function getInputHTML( $value ) {
2270 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
2271
2272 # If one of the options' 'name' is int(0), it is automatically selected.
2273 # because PHP sucks and thinks int(0) == 'some string'.
2274 # Working around this by forcing all of them to strings.
2275 foreach ( $this->mParams['options'] as &$opt ) {
2276 if ( is_int( $opt ) ) {
2277 $opt = strval( $opt );
2278 }
2279 }
2280 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2281
2282 if ( !empty( $this->mParams['disabled'] ) ) {
2283 $select->setAttribute( 'disabled', 'disabled' );
2284 }
2285
2286 if ( $this->mClass !== '' ) {
2287 $select->setAttribute( 'class', $this->mClass );
2288 }
2289
2290 $select->addOptions( $this->mParams['options'] );
2291
2292 return $select->getHTML();
2293 }
2294 }
2295
2296 /**
2297 * Select dropdown field, with an additional "other" textbox.
2298 */
2299 class HTMLSelectOrOtherField extends HTMLTextField {
2300
2301 function __construct( $params ) {
2302 if ( !in_array( 'other', $params['options'], true ) ) {
2303 $msg = isset( $params['other'] ) ?
2304 $params['other'] :
2305 wfMessage( 'htmlform-selectorother-other' )->text();
2306 $params['options'][$msg] = 'other';
2307 }
2308
2309 parent::__construct( $params );
2310 }
2311
2312 static function forceToStringRecursive( $array ) {
2313 if ( is_array( $array ) ) {
2314 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
2315 } else {
2316 return strval( $array );
2317 }
2318 }
2319
2320 function getInputHTML( $value ) {
2321 $valInSelect = false;
2322
2323 if ( $value !== false ) {
2324 $valInSelect = in_array(
2325 $value,
2326 HTMLFormField::flattenOptions( $this->mParams['options'] )
2327 );
2328 }
2329
2330 $selected = $valInSelect ? $value : 'other';
2331
2332 $opts = self::forceToStringRecursive( $this->mParams['options'] );
2333
2334 $select = new XmlSelect( $this->mName, $this->mID, $selected );
2335 $select->addOptions( $opts );
2336
2337 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2338
2339 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
2340
2341 if ( !empty( $this->mParams['disabled'] ) ) {
2342 $select->setAttribute( 'disabled', 'disabled' );
2343 $tbAttribs['disabled'] = 'disabled';
2344 }
2345
2346 $select = $select->getHTML();
2347
2348 if ( isset( $this->mParams['maxlength'] ) ) {
2349 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
2350 }
2351
2352 if ( $this->mClass !== '' ) {
2353 $tbAttribs['class'] = $this->mClass;
2354 }
2355
2356 $textbox = Html::input(
2357 $this->mName . '-other',
2358 $valInSelect ? '' : $value,
2359 'text',
2360 $tbAttribs
2361 );
2362
2363 return "$select<br />\n$textbox";
2364 }
2365
2366 /**
2367 * @param $request WebRequest
2368 * @return String
2369 */
2370 function loadDataFromRequest( $request ) {
2371 if ( $request->getCheck( $this->mName ) ) {
2372 $val = $request->getText( $this->mName );
2373
2374 if ( $val == 'other' ) {
2375 $val = $request->getText( $this->mName . '-other' );
2376 }
2377
2378 return $val;
2379 } else {
2380 return $this->getDefault();
2381 }
2382 }
2383 }
2384
2385 /**
2386 * Multi-select field
2387 */
2388 class HTMLMultiSelectField extends HTMLFormField implements HTMLNestedFilterable {
2389
2390 function validate( $value, $alldata ) {
2391 $p = parent::validate( $value, $alldata );
2392
2393 if ( $p !== true ) {
2394 return $p;
2395 }
2396
2397 if ( !is_array( $value ) ) {
2398 return false;
2399 }
2400
2401 # If all options are valid, array_intersect of the valid options
2402 # and the provided options will return the provided options.
2403 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2404
2405 $validValues = array_intersect( $value, $validOptions );
2406 if ( count( $validValues ) == count( $value ) ) {
2407 return true;
2408 } else {
2409 return $this->msg( 'htmlform-select-badoption' )->parse();
2410 }
2411 }
2412
2413 function getInputHTML( $value ) {
2414 $html = $this->formatOptions( $this->mParams['options'], $value );
2415
2416 return $html;
2417 }
2418
2419 function formatOptions( $options, $value ) {
2420 $html = '';
2421
2422 $attribs = array();
2423
2424 if ( !empty( $this->mParams['disabled'] ) ) {
2425 $attribs['disabled'] = 'disabled';
2426 }
2427
2428 foreach ( $options as $label => $info ) {
2429 if ( is_array( $info ) ) {
2430 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2431 $html .= $this->formatOptions( $info, $value );
2432 } else {
2433 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2434
2435 $checkbox = Xml::check(
2436 $this->mName . '[]',
2437 in_array( $info, $value, true ),
2438 $attribs + $thisAttribs );
2439 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2440
2441 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2442 }
2443 }
2444
2445 return $html;
2446 }
2447
2448 /**
2449 * @param $request WebRequest
2450 * @return String
2451 */
2452 function loadDataFromRequest( $request ) {
2453 if ( $this->mParent->getMethod() == 'post' ) {
2454 if ( $request->wasPosted() ) {
2455 # Checkboxes are just not added to the request arrays if they're not checked,
2456 # so it's perfectly possible for there not to be an entry at all
2457 return $request->getArray( $this->mName, array() );
2458 } else {
2459 # That's ok, the user has not yet submitted the form, so show the defaults
2460 return $this->getDefault();
2461 }
2462 } else {
2463 # This is the impossible case: if we look at $_GET and see no data for our
2464 # field, is it because the user has not yet submitted the form, or that they
2465 # have submitted it with all the options unchecked? We will have to assume the
2466 # latter, which basically means that you can't specify 'positive' defaults
2467 # for GET forms.
2468 # @todo FIXME...
2469 return $request->getArray( $this->mName, array() );
2470 }
2471 }
2472
2473 function getDefault() {
2474 if ( isset( $this->mDefault ) ) {
2475 return $this->mDefault;
2476 } else {
2477 return array();
2478 }
2479 }
2480
2481 function filterDataForSubmit( $data ) {
2482 $options = HTMLFormField::flattenOptions( $this->mParams['options'] );
2483
2484 $res = array();
2485 foreach ( $options as $opt ) {
2486 $res["$opt"] = in_array( $opt, $data );
2487 }
2488
2489 return $res;
2490 }
2491
2492 protected function needsLabel() {
2493 return false;
2494 }
2495 }
2496
2497 /**
2498 * Double field with a dropdown list constructed from a system message in the format
2499 * * Optgroup header
2500 * ** <option value>
2501 * * New Optgroup header
2502 * Plus a text field underneath for an additional reason. The 'value' of the field is
2503 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2504 * select dropdown.
2505 * @todo FIXME: If made 'required', only the text field should be compulsory.
2506 */
2507 class HTMLSelectAndOtherField extends HTMLSelectField {
2508
2509 function __construct( $params ) {
2510 if ( array_key_exists( 'other', $params ) ) {
2511 } elseif ( array_key_exists( 'other-message', $params ) ) {
2512 $params['other'] = wfMessage( $params['other-message'] )->plain();
2513 } else {
2514 $params['other'] = null;
2515 }
2516
2517 if ( array_key_exists( 'options', $params ) ) {
2518 # Options array already specified
2519 } elseif ( array_key_exists( 'options-message', $params ) ) {
2520 # Generate options array from a system message
2521 $params['options'] = self::parseMessage(
2522 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2523 $params['other']
2524 );
2525 } else {
2526 # Sulk
2527 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2528 }
2529 $this->mFlatOptions = self::flattenOptions( $params['options'] );
2530
2531 parent::__construct( $params );
2532 }
2533
2534 /**
2535 * Build a drop-down box from a textual list.
2536 * @param string $string message text
2537 * @param string $otherName name of "other reason" option
2538 * @return Array
2539 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2540 */
2541 public static function parseMessage( $string, $otherName = null ) {
2542 if ( $otherName === null ) {
2543 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2544 }
2545
2546 $optgroup = false;
2547 $options = array( $otherName => 'other' );
2548
2549 foreach ( explode( "\n", $string ) as $option ) {
2550 $value = trim( $option );
2551 if ( $value == '' ) {
2552 continue;
2553 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2554 # A new group is starting...
2555 $value = trim( substr( $value, 1 ) );
2556 $optgroup = $value;
2557 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2558 # groupmember
2559 $opt = trim( substr( $value, 2 ) );
2560 if ( $optgroup === false ) {
2561 $options[$opt] = $opt;
2562 } else {
2563 $options[$optgroup][$opt] = $opt;
2564 }
2565 } else {
2566 # groupless reason list
2567 $optgroup = false;
2568 $options[$option] = $option;
2569 }
2570 }
2571
2572 return $options;
2573 }
2574
2575 function getInputHTML( $value ) {
2576 $select = parent::getInputHTML( $value[1] );
2577
2578 $textAttribs = array(
2579 'id' => $this->mID . '-other',
2580 'size' => $this->getSize(),
2581 );
2582
2583 if ( $this->mClass !== '' ) {
2584 $textAttribs['class'] = $this->mClass;
2585 }
2586
2587 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2588 if ( isset( $this->mParams[$param] ) ) {
2589 $textAttribs[$param] = '';
2590 }
2591 }
2592
2593 $textbox = Html::input(
2594 $this->mName . '-other',
2595 $value[2],
2596 'text',
2597 $textAttribs
2598 );
2599
2600 return "$select<br />\n$textbox";
2601 }
2602
2603 /**
2604 * @param $request WebRequest
2605 * @return Array("<overall message>","<select value>","<text field value>")
2606 */
2607 function loadDataFromRequest( $request ) {
2608 if ( $request->getCheck( $this->mName ) ) {
2609
2610 $list = $request->getText( $this->mName );
2611 $text = $request->getText( $this->mName . '-other' );
2612
2613 if ( $list == 'other' ) {
2614 $final = $text;
2615 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2616 # User has spoofed the select form to give an option which wasn't
2617 # in the original offer. Sulk...
2618 $final = $text;
2619 } elseif ( $text == '' ) {
2620 $final = $list;
2621 } else {
2622 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2623 }
2624
2625 } else {
2626 $final = $this->getDefault();
2627
2628 $list = 'other';
2629 $text = $final;
2630 foreach ( $this->mFlatOptions as $option ) {
2631 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2632 if ( strpos( $text, $match ) === 0 ) {
2633 $list = $option;
2634 $text = substr( $text, strlen( $match ) );
2635 break;
2636 }
2637 }
2638 }
2639 return array( $final, $list, $text );
2640 }
2641
2642 function getSize() {
2643 return isset( $this->mParams['size'] )
2644 ? $this->mParams['size']
2645 : 45;
2646 }
2647
2648 function validate( $value, $alldata ) {
2649 # HTMLSelectField forces $value to be one of the options in the select
2650 # field, which is not useful here. But we do want the validation further up
2651 # the chain
2652 $p = parent::validate( $value[1], $alldata );
2653
2654 if ( $p !== true ) {
2655 return $p;
2656 }
2657
2658 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value[1] === '' ) {
2659 return $this->msg( 'htmlform-required' )->parse();
2660 }
2661
2662 return true;
2663 }
2664 }
2665
2666 /**
2667 * Radio checkbox fields.
2668 */
2669 class HTMLRadioField extends HTMLFormField {
2670
2671 function validate( $value, $alldata ) {
2672 $p = parent::validate( $value, $alldata );
2673
2674 if ( $p !== true ) {
2675 return $p;
2676 }
2677
2678 if ( !is_string( $value ) && !is_int( $value ) ) {
2679 return false;
2680 }
2681
2682 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2683
2684 if ( in_array( $value, $validOptions ) ) {
2685 return true;
2686 } else {
2687 return $this->msg( 'htmlform-select-badoption' )->parse();
2688 }
2689 }
2690
2691 /**
2692 * This returns a block of all the radio options, in one cell.
2693 * @see includes/HTMLFormField#getInputHTML()
2694 * @param $value String
2695 * @return String
2696 */
2697 function getInputHTML( $value ) {
2698 $html = $this->formatOptions( $this->mParams['options'], $value );
2699
2700 return $html;
2701 }
2702
2703 function formatOptions( $options, $value ) {
2704 $html = '';
2705
2706 $attribs = array();
2707 if ( !empty( $this->mParams['disabled'] ) ) {
2708 $attribs['disabled'] = 'disabled';
2709 }
2710
2711 # TODO: should this produce an unordered list perhaps?
2712 foreach ( $options as $label => $info ) {
2713 if ( is_array( $info ) ) {
2714 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2715 $html .= $this->formatOptions( $info, $value );
2716 } else {
2717 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2718 $radio = Xml::radio(
2719 $this->mName,
2720 $info,
2721 $info == $value,
2722 $attribs + array( 'id' => $id )
2723 );
2724 $radio .= '&#160;' .
2725 Html::rawElement( 'label', array( 'for' => $id ), $label );
2726
2727 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2728 }
2729 }
2730
2731 return $html;
2732 }
2733
2734 protected function needsLabel() {
2735 return false;
2736 }
2737 }
2738
2739 /**
2740 * An information field (text blob), not a proper input.
2741 */
2742 class HTMLInfoField extends HTMLFormField {
2743 public function __construct( $info ) {
2744 $info['nodata'] = true;
2745
2746 parent::__construct( $info );
2747 }
2748
2749 public function getInputHTML( $value ) {
2750 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2751 }
2752
2753 public function getTableRow( $value ) {
2754 if ( !empty( $this->mParams['rawrow'] ) ) {
2755 return $value;
2756 }
2757
2758 return parent::getTableRow( $value );
2759 }
2760
2761 /**
2762 * @since 1.20
2763 */
2764 public function getDiv( $value ) {
2765 if ( !empty( $this->mParams['rawrow'] ) ) {
2766 return $value;
2767 }
2768
2769 return parent::getDiv( $value );
2770 }
2771
2772 /**
2773 * @since 1.20
2774 */
2775 public function getRaw( $value ) {
2776 if ( !empty( $this->mParams['rawrow'] ) ) {
2777 return $value;
2778 }
2779
2780 return parent::getRaw( $value );
2781 }
2782
2783 protected function needsLabel() {
2784 return false;
2785 }
2786 }
2787
2788 class HTMLHiddenField extends HTMLFormField {
2789 public function __construct( $params ) {
2790 parent::__construct( $params );
2791
2792 # Per HTML5 spec, hidden fields cannot be 'required'
2793 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2794 unset( $this->mParams['required'] );
2795 }
2796
2797 public function getTableRow( $value ) {
2798 $params = array();
2799 if ( $this->mID ) {
2800 $params['id'] = $this->mID;
2801 }
2802
2803 $this->mParent->addHiddenField(
2804 $this->mName,
2805 $this->mDefault,
2806 $params
2807 );
2808
2809 return '';
2810 }
2811
2812 /**
2813 * @since 1.20
2814 */
2815 public function getDiv( $value ) {
2816 return $this->getTableRow( $value );
2817 }
2818
2819 /**
2820 * @since 1.20
2821 */
2822 public function getRaw( $value ) {
2823 return $this->getTableRow( $value );
2824 }
2825
2826 public function getInputHTML( $value ) {
2827 return '';
2828 }
2829 }
2830
2831 /**
2832 * Add a submit button inline in the form (as opposed to
2833 * HTMLForm::addButton(), which will add it at the end).
2834 */
2835 class HTMLSubmitField extends HTMLButtonField {
2836 protected $buttonType = 'submit';
2837 }
2838
2839 /**
2840 * Adds a generic button inline to the form. Does not do anything, you must add
2841 * click handling code in JavaScript. Use a HTMLSubmitField if you merely
2842 * wish to add a submit button to a form.
2843 *
2844 * @since 1.22
2845 */
2846 class HTMLButtonField extends HTMLFormField {
2847 protected $buttonType = 'button';
2848
2849 public function __construct( $info ) {
2850 $info['nodata'] = true;
2851 parent::__construct( $info );
2852 }
2853
2854 public function getInputHTML( $value ) {
2855 $attr = array(
2856 'class' => 'mw-htmlform-submit ' . $this->mClass,
2857 'id' => $this->mID,
2858 );
2859
2860 if ( !empty( $this->mParams['disabled'] ) ) {
2861 $attr['disabled'] = 'disabled';
2862 }
2863
2864 return Html::input(
2865 $this->mName,
2866 $value,
2867 $this->buttonType,
2868 $attr
2869 );
2870 }
2871
2872 protected function needsLabel() {
2873 return false;
2874 }
2875
2876 /**
2877 * Button cannot be invalid
2878 * @param $value String
2879 * @param $alldata Array
2880 * @return Bool
2881 */
2882 public function validate( $value, $alldata ) {
2883 return true;
2884 }
2885 }
2886
2887 class HTMLEditTools extends HTMLFormField {
2888 public function getInputHTML( $value ) {
2889 return '';
2890 }
2891
2892 public function getTableRow( $value ) {
2893 $msg = $this->formatMsg();
2894
2895 return '<tr><td></td><td class="mw-input">'
2896 . '<div class="mw-editTools">'
2897 . $msg->parseAsBlock()
2898 . "</div></td></tr>\n";
2899 }
2900
2901 /**
2902 * @since 1.20
2903 */
2904 public function getDiv( $value ) {
2905 $msg = $this->formatMsg();
2906 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2907 }
2908
2909 /**
2910 * @since 1.20
2911 */
2912 public function getRaw( $value ) {
2913 return $this->getDiv( $value );
2914 }
2915
2916 protected function formatMsg() {
2917 if ( empty( $this->mParams['message'] ) ) {
2918 $msg = $this->msg( 'edittools' );
2919 } else {
2920 $msg = $this->msg( $this->mParams['message'] );
2921 if ( $msg->isDisabled() ) {
2922 $msg = $this->msg( 'edittools' );
2923 }
2924 }
2925 $msg->inContentLanguage();
2926 return $msg;
2927 }
2928 }
2929
2930 class HTMLApiField extends HTMLFormField {
2931 public function getTableRow( $value ) {
2932 return '';
2933 }
2934
2935 public function getDiv( $value ) {
2936 return $this->getTableRow( $value );
2937 }
2938
2939 public function getRaw( $value ) {
2940 return $this->getTableRow( $value );
2941 }
2942
2943 public function getInputHTML( $value ) {
2944 return '';
2945 }
2946 }
2947
2948 interface HTMLNestedFilterable {
2949 /**
2950 * Support for seperating multi-option preferences into multiple preferences
2951 * Due to lack of array support.
2952 * @param $data array
2953 */
2954 function filterDataForSubmit( $data );
2955 }
2956
2957 class HTMLFormFieldRequiredOptionsException extends MWException {
2958 public function __construct( HTMLFormField $field, array $missing ) {
2959 parent::__construct( sprintf(
2960 "Form type `%s` expected the following parameters to be set: %s",
2961 get_class( $field ),
2962 implode( ', ', $missing )
2963 ) );
2964 }
2965 }