Merge "Show tags on deleted edits through the API"
[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 $html = $this->wrapForm( $html );
661
662 return '' . $this->mPre . $html . $this->mPost;
663 }
664
665 /**
666 * Wrap the form innards in an actual "<form>" element
667 * @param string $html HTML contents to wrap.
668 * @return String wrapped HTML.
669 */
670 function wrapForm( $html ) {
671
672 # Include a <fieldset> wrapper for style, if requested.
673 if ( $this->mWrapperLegend !== false ) {
674 $html = Xml::fieldset( $this->mWrapperLegend, $html );
675 }
676 # Use multipart/form-data
677 $encType = $this->mUseMultipart
678 ? 'multipart/form-data'
679 : 'application/x-www-form-urlencoded';
680 # Attributes
681 $attribs = array(
682 'action' => $this->getAction(),
683 'method' => $this->getMethod(),
684 'class' => array( 'visualClear' ),
685 'enctype' => $encType,
686 );
687 if ( !empty( $this->mId ) ) {
688 $attribs['id'] = $this->mId;
689 }
690
691 if ( $this->isVForm() ) {
692 array_push( $attribs['class'], 'mw-ui-vform', 'mw-ui-container' );
693 }
694 return Html::rawElement( 'form', $attribs, $html );
695 }
696
697 /**
698 * Get the hidden fields that should go inside the form.
699 * @return String HTML.
700 */
701 function getHiddenFields() {
702 global $wgArticlePath;
703
704 $html = '';
705 if ( $this->getMethod() == 'post' ) {
706 $html .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
707 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
708 }
709
710 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() == 'get' ) {
711 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
712 }
713
714 foreach ( $this->mHiddenFields as $data ) {
715 list( $value, $attribs ) = $data;
716 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
717 }
718
719 return $html;
720 }
721
722 /**
723 * Get the submit and (potentially) reset buttons.
724 * @return String HTML.
725 */
726 function getButtons() {
727 $html = '<span class="mw-htmlform-submit-buttons">';
728
729 if ( $this->mShowSubmit ) {
730 $attribs = array();
731
732 if ( isset( $this->mSubmitID ) ) {
733 $attribs['id'] = $this->mSubmitID;
734 }
735
736 if ( isset( $this->mSubmitName ) ) {
737 $attribs['name'] = $this->mSubmitName;
738 }
739
740 if ( isset( $this->mSubmitTooltip ) ) {
741 $attribs += Linker::tooltipAndAccesskeyAttribs( $this->mSubmitTooltip );
742 }
743
744 $attribs['class'] = array( 'mw-htmlform-submit' );
745
746 if ( $this->isVForm() ) {
747 // mw-ui-block is necessary because the buttons aren't necessarily in an
748 // immediate child div of the vform.
749 array_push( $attribs['class'], 'mw-ui-button', 'mw-ui-big', 'mw-ui-primary', 'mw-ui-block' );
750 }
751
752 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
753
754 // Buttons are top-level form elements in table and div layouts,
755 // but vform wants all elements inside divs to get spaced-out block
756 // styling.
757 if ( $this->isVForm() ) {
758 $html = Html::rawElement( 'div', null, "\n$html\n" );
759 }
760 }
761
762 if ( $this->mShowReset ) {
763 $html .= Html::element(
764 'input',
765 array(
766 'type' => 'reset',
767 'value' => $this->msg( 'htmlform-reset' )->text()
768 )
769 ) . "\n";
770 }
771
772 foreach ( $this->mButtons as $button ) {
773 $attrs = array(
774 'type' => 'submit',
775 'name' => $button['name'],
776 'value' => $button['value']
777 );
778
779 if ( $button['attribs'] ) {
780 $attrs += $button['attribs'];
781 }
782
783 if ( isset( $button['id'] ) ) {
784 $attrs['id'] = $button['id'];
785 }
786
787 $html .= Html::element( 'input', $attrs );
788 }
789
790 $html .= '</span>';
791
792 return $html;
793 }
794
795 /**
796 * Get the whole body of the form.
797 * @return String
798 */
799 function getBody() {
800 return $this->displaySection( $this->mFieldTree, $this->mTableId );
801 }
802
803 /**
804 * Format and display an error message stack.
805 * @param $errors String|Array|Status
806 * @return String
807 */
808 function getErrors( $errors ) {
809 if ( $errors instanceof Status ) {
810 if ( $errors->isOK() ) {
811 $errorstr = '';
812 } else {
813 $errorstr = $this->getOutput()->parse( $errors->getWikiText() );
814 }
815 } elseif ( is_array( $errors ) ) {
816 $errorstr = $this->formatErrors( $errors );
817 } else {
818 $errorstr = $errors;
819 }
820
821 return $errorstr
822 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
823 : '';
824 }
825
826 /**
827 * Format a stack of error messages into a single HTML string
828 * @param array $errors of message keys/values
829 * @return String HTML, a "<ul>" list of errors
830 */
831 public static function formatErrors( $errors ) {
832 $errorstr = '';
833
834 foreach ( $errors as $error ) {
835 if ( is_array( $error ) ) {
836 $msg = array_shift( $error );
837 } else {
838 $msg = $error;
839 $error = array();
840 }
841
842 $errorstr .= Html::rawElement(
843 'li',
844 array(),
845 wfMessage( $msg, $error )->parse()
846 );
847 }
848
849 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
850
851 return $errorstr;
852 }
853
854 /**
855 * Set the text for the submit button
856 * @param string $t plaintext.
857 * @return HTMLForm $this for chaining calls (since 1.20)
858 */
859 function setSubmitText( $t ) {
860 $this->mSubmitText = $t;
861 return $this;
862 }
863
864 /**
865 * Set the text for the submit button to a message
866 * @since 1.19
867 * @param string $msg message key
868 * @return HTMLForm $this for chaining calls (since 1.20)
869 */
870 public function setSubmitTextMsg( $msg ) {
871 $this->setSubmitText( $this->msg( $msg )->text() );
872 return $this;
873 }
874
875 /**
876 * Get the text for the submit button, either customised or a default.
877 * @return string
878 */
879 function getSubmitText() {
880 return $this->mSubmitText
881 ? $this->mSubmitText
882 : $this->msg( 'htmlform-submit' )->text();
883 }
884
885 /**
886 * @param string $name Submit button name
887 * @return HTMLForm $this for chaining calls (since 1.20)
888 */
889 public function setSubmitName( $name ) {
890 $this->mSubmitName = $name;
891 return $this;
892 }
893
894 /**
895 * @param string $name Tooltip for the submit button
896 * @return HTMLForm $this for chaining calls (since 1.20)
897 */
898 public function setSubmitTooltip( $name ) {
899 $this->mSubmitTooltip = $name;
900 return $this;
901 }
902
903 /**
904 * Set the id for the submit button.
905 * @param $t String.
906 * @todo FIXME: Integrity of $t is *not* validated
907 * @return HTMLForm $this for chaining calls (since 1.20)
908 */
909 function setSubmitID( $t ) {
910 $this->mSubmitID = $t;
911 return $this;
912 }
913
914 /**
915 * Stop a default submit button being shown for this form. This implies that an
916 * alternate submit method must be provided manually.
917 *
918 * @since 1.22
919 *
920 * @param bool $suppressSubmit Set to false to re-enable the button again
921 *
922 * @return HTMLForm $this for chaining calls
923 */
924 function suppressDefaultSubmit( $suppressSubmit = true ) {
925 $this->mShowSubmit = !$suppressSubmit;
926 return $this;
927 }
928
929 /**
930 * Set the id of the \<table\> or outermost \<div\> element.
931 *
932 * @since 1.22
933 * @param string $id new value of the id attribute, or "" to remove
934 * @return HTMLForm $this for chaining calls
935 */
936 public function setTableId( $id ) {
937 $this->mTableId = $id;
938 return $this;
939 }
940
941 /**
942 * @param string $id DOM id for the form
943 * @return HTMLForm $this for chaining calls (since 1.20)
944 */
945 public function setId( $id ) {
946 $this->mId = $id;
947 return $this;
948 }
949
950 /**
951 * Prompt the whole form to be wrapped in a "<fieldset>", with
952 * this text as its "<legend>" element.
953 * @param string|false $legend HTML to go inside the "<legend>" element, or
954 * false for no <legend>
955 * Will be escaped
956 * @return HTMLForm $this for chaining calls (since 1.20)
957 */
958 public function setWrapperLegend( $legend ) {
959 $this->mWrapperLegend = $legend;
960 return $this;
961 }
962
963 /**
964 * Prompt the whole form to be wrapped in a "<fieldset>", with
965 * this message as its "<legend>" element.
966 * @since 1.19
967 * @param string $msg message key
968 * @return HTMLForm $this for chaining calls (since 1.20)
969 */
970 public function setWrapperLegendMsg( $msg ) {
971 $this->setWrapperLegend( $this->msg( $msg )->text() );
972 return $this;
973 }
974
975 /**
976 * Set the prefix for various default messages
977 * @todo currently only used for the "<fieldset>" legend on forms
978 * with multiple sections; should be used elsewhere?
979 * @param $p String
980 * @return HTMLForm $this for chaining calls (since 1.20)
981 */
982 function setMessagePrefix( $p ) {
983 $this->mMessagePrefix = $p;
984 return $this;
985 }
986
987 /**
988 * Set the title for form submission
989 * @param $t Title of page the form is on/should be posted to
990 * @return HTMLForm $this for chaining calls (since 1.20)
991 */
992 function setTitle( $t ) {
993 $this->mTitle = $t;
994 return $this;
995 }
996
997 /**
998 * Get the title
999 * @return Title
1000 */
1001 function getTitle() {
1002 return $this->mTitle === false
1003 ? $this->getContext()->getTitle()
1004 : $this->mTitle;
1005 }
1006
1007 /**
1008 * Set the method used to submit the form
1009 * @param $method String
1010 * @return HTMLForm $this for chaining calls (since 1.20)
1011 */
1012 public function setMethod( $method = 'post' ) {
1013 $this->mMethod = $method;
1014 return $this;
1015 }
1016
1017 public function getMethod() {
1018 return $this->mMethod;
1019 }
1020
1021 /**
1022 * @todo Document
1023 * @param array[]|HTMLFormField[] $fields array of fields (either arrays or objects)
1024 * @param string $sectionName ID attribute of the "<table>" tag for this section, ignored if empty
1025 * @param string $fieldsetIDPrefix ID prefix for the "<fieldset>" tag of each subsection, ignored if empty
1026 * @param boolean &$hasUserVisibleFields Whether the section had user-visible fields
1027 * @return String
1028 */
1029 public function displaySection( $fields, $sectionName = '', $fieldsetIDPrefix = '', &$hasUserVisibleFields = false ) {
1030 $displayFormat = $this->getDisplayFormat();
1031
1032 $html = '';
1033 $subsectionHtml = '';
1034 $hasLabel = false;
1035
1036 switch ( $displayFormat ) {
1037 case 'table':
1038 $getFieldHtmlMethod = 'getTableRow';
1039 break;
1040 case 'vform':
1041 // Close enough to a div.
1042 $getFieldHtmlMethod = 'getDiv';
1043 break;
1044 default:
1045 $getFieldHtmlMethod = 'get' . ucfirst( $displayFormat );
1046 }
1047
1048 foreach ( $fields as $key => $value ) {
1049 if ( $value instanceof HTMLFormField ) {
1050 $v = empty( $value->mParams['nodata'] )
1051 ? $this->mFieldData[$key]
1052 : $value->getDefault();
1053 $html .= $value->$getFieldHtmlMethod( $v );
1054
1055 $labelValue = trim( $value->getLabel() );
1056 if ( $labelValue != '&#160;' && $labelValue !== '' ) {
1057 $hasLabel = true;
1058 }
1059
1060 if ( get_class( $value ) !== 'HTMLHiddenField' &&
1061 get_class( $value ) !== 'HTMLApiField' ) {
1062 $hasUserVisibleFields = true;
1063 }
1064 } elseif ( is_array( $value ) ) {
1065 $subsectionHasVisibleFields = false;
1066 $section = $this->displaySection( $value, "mw-htmlform-$key", "$fieldsetIDPrefix$key-", $subsectionHasVisibleFields );
1067 $legend = null;
1068
1069 if ( $subsectionHasVisibleFields === true ) {
1070 // Display the section with various niceties.
1071 $hasUserVisibleFields = true;
1072
1073 $legend = $this->getLegend( $key );
1074
1075 if ( isset( $this->mSectionHeaders[$key] ) ) {
1076 $section = $this->mSectionHeaders[$key] . $section;
1077 }
1078 if ( isset( $this->mSectionFooters[$key] ) ) {
1079 $section .= $this->mSectionFooters[$key];
1080 }
1081
1082 $attributes = array();
1083 if ( $fieldsetIDPrefix ) {
1084 $attributes['id'] = Sanitizer::escapeId( "$fieldsetIDPrefix$key" );
1085 }
1086 $subsectionHtml .= Xml::fieldset( $legend, $section, $attributes ) . "\n";
1087 } else {
1088 // Just return the inputs, nothing fancy.
1089 $subsectionHtml .= $section;
1090 }
1091 }
1092 }
1093
1094 if ( $displayFormat !== 'raw' ) {
1095 $classes = array();
1096
1097 if ( !$hasLabel ) { // Avoid strange spacing when no labels exist
1098 $classes[] = 'mw-htmlform-nolabel';
1099 }
1100
1101 $attribs = array(
1102 'class' => implode( ' ', $classes ),
1103 );
1104
1105 if ( $sectionName ) {
1106 $attribs['id'] = Sanitizer::escapeId( $sectionName );
1107 }
1108
1109 if ( $displayFormat === 'table' ) {
1110 $html = Html::rawElement( 'table', $attribs,
1111 Html::rawElement( 'tbody', array(), "\n$html\n" ) ) . "\n";
1112 } elseif ( $displayFormat === 'div' || $displayFormat === 'vform' ) {
1113 $html = Html::rawElement( 'div', $attribs, "\n$html\n" );
1114 }
1115 }
1116
1117 if ( $this->mSubSectionBeforeFields ) {
1118 return $subsectionHtml . "\n" . $html;
1119 } else {
1120 return $html . "\n" . $subsectionHtml;
1121 }
1122 }
1123
1124 /**
1125 * Construct the form fields from the Descriptor array
1126 */
1127 function loadData() {
1128 $fieldData = array();
1129
1130 foreach ( $this->mFlatFields as $fieldname => $field ) {
1131 if ( !empty( $field->mParams['nodata'] ) ) {
1132 continue;
1133 } elseif ( !empty( $field->mParams['disabled'] ) ) {
1134 $fieldData[$fieldname] = $field->getDefault();
1135 } else {
1136 $fieldData[$fieldname] = $field->loadDataFromRequest( $this->getRequest() );
1137 }
1138 }
1139
1140 # Filter data.
1141 foreach ( $fieldData as $name => &$value ) {
1142 $field = $this->mFlatFields[$name];
1143 $value = $field->filter( $value, $this->mFlatFields );
1144 }
1145
1146 $this->mFieldData = $fieldData;
1147 }
1148
1149 /**
1150 * Stop a reset button being shown for this form
1151 * @param bool $suppressReset set to false to re-enable the
1152 * button again
1153 * @return HTMLForm $this for chaining calls (since 1.20)
1154 */
1155 function suppressReset( $suppressReset = true ) {
1156 $this->mShowReset = !$suppressReset;
1157 return $this;
1158 }
1159
1160 /**
1161 * Overload this if you want to apply special filtration routines
1162 * to the form as a whole, after it's submitted but before it's
1163 * processed.
1164 * @param $data
1165 * @return
1166 */
1167 function filterDataForSubmit( $data ) {
1168 return $data;
1169 }
1170
1171 /**
1172 * Get a string to go in the "<legend>" of a section fieldset.
1173 * Override this if you want something more complicated.
1174 * @param $key String
1175 * @return String
1176 */
1177 public function getLegend( $key ) {
1178 return $this->msg( "{$this->mMessagePrefix}-$key" )->text();
1179 }
1180
1181 /**
1182 * Set the value for the action attribute of the form.
1183 * When set to false (which is the default state), the set title is used.
1184 *
1185 * @since 1.19
1186 *
1187 * @param string|bool $action
1188 * @return HTMLForm $this for chaining calls (since 1.20)
1189 */
1190 public function setAction( $action ) {
1191 $this->mAction = $action;
1192 return $this;
1193 }
1194
1195 /**
1196 * Get the value for the action attribute of the form.
1197 *
1198 * @since 1.22
1199 *
1200 * @return string
1201 */
1202 public function getAction() {
1203 global $wgScript, $wgArticlePath;
1204
1205 // If an action is alredy provided, return it
1206 if ( $this->mAction !== false ) {
1207 return $this->mAction;
1208 }
1209
1210 // Check whether we are in GET mode and $wgArticlePath contains a "?"
1211 // meaning that getLocalURL() would return something like "index.php?title=...".
1212 // As browser remove the query string before submitting GET forms,
1213 // it means that the title would be lost. In such case use $wgScript instead
1214 // and put title in an hidden field (see getHiddenFields()).
1215 if ( strpos( $wgArticlePath, '?' ) !== false && $this->getMethod() === 'get' ) {
1216 return $wgScript;
1217 }
1218
1219 return $this->getTitle()->getLocalURL();
1220 }
1221 }
1222
1223 /**
1224 * The parent class to generate form fields. Any field type should
1225 * be a subclass of this.
1226 */
1227 abstract class HTMLFormField {
1228
1229 protected $mValidationCallback;
1230 protected $mFilterCallback;
1231 protected $mName;
1232 public $mParams;
1233 protected $mLabel; # String label. Set on construction
1234 protected $mID;
1235 protected $mClass = '';
1236 protected $mDefault;
1237
1238 /**
1239 * @var bool If true will generate an empty div element with no label
1240 * @since 1.22
1241 */
1242 protected $mShowEmptyLabels = true;
1243
1244 /**
1245 * @var HTMLForm
1246 */
1247 public $mParent;
1248
1249 /**
1250 * This function must be implemented to return the HTML to generate
1251 * the input object itself. It should not implement the surrounding
1252 * table cells/rows, or labels/help messages.
1253 * @param string $value the value to set the input to; eg a default
1254 * text for a text input.
1255 * @return String valid HTML.
1256 */
1257 abstract function getInputHTML( $value );
1258
1259 /**
1260 * Get a translated interface message
1261 *
1262 * This is a wrapper around $this->mParent->msg() if $this->mParent is set
1263 * and wfMessage() otherwise.
1264 *
1265 * Parameters are the same as wfMessage().
1266 *
1267 * @return Message object
1268 */
1269 function msg() {
1270 $args = func_get_args();
1271
1272 if ( $this->mParent ) {
1273 $callback = array( $this->mParent, 'msg' );
1274 } else {
1275 $callback = 'wfMessage';
1276 }
1277
1278 return call_user_func_array( $callback, $args );
1279 }
1280
1281 /**
1282 * Override this function to add specific validation checks on the
1283 * field input. Don't forget to call parent::validate() to ensure
1284 * that the user-defined callback mValidationCallback is still run
1285 * @param string $value the value the field was submitted with
1286 * @param array $alldata the data collected from the form
1287 * @return Mixed Bool true on success, or String error to display.
1288 */
1289 function validate( $value, $alldata ) {
1290 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value === '' ) {
1291 return $this->msg( 'htmlform-required' )->parse();
1292 }
1293
1294 if ( isset( $this->mValidationCallback ) ) {
1295 return call_user_func( $this->mValidationCallback, $value, $alldata, $this->mParent );
1296 }
1297
1298 return true;
1299 }
1300
1301 function filter( $value, $alldata ) {
1302 if ( isset( $this->mFilterCallback ) ) {
1303 $value = call_user_func( $this->mFilterCallback, $value, $alldata, $this->mParent );
1304 }
1305
1306 return $value;
1307 }
1308
1309 /**
1310 * Should this field have a label, or is there no input element with the
1311 * appropriate id for the label to point to?
1312 *
1313 * @return bool True to output a label, false to suppress
1314 */
1315 protected function needsLabel() {
1316 return true;
1317 }
1318
1319 /**
1320 * Tell the field whether to generate a separate label element if its label
1321 * is blank.
1322 *
1323 * @since 1.22
1324 * @param bool $show Set to false to not generate a label.
1325 * @return void
1326 */
1327 public function setShowEmptyLabel( $show ) {
1328 $this->mShowEmptyLabels = $show;
1329 }
1330
1331 /**
1332 * Get the value that this input has been set to from a posted form,
1333 * or the input's default value if it has not been set.
1334 * @param $request WebRequest
1335 * @return String the value
1336 */
1337 function loadDataFromRequest( $request ) {
1338 if ( $request->getCheck( $this->mName ) ) {
1339 return $request->getText( $this->mName );
1340 } else {
1341 return $this->getDefault();
1342 }
1343 }
1344
1345 /**
1346 * Initialise the object
1347 * @param array $params Associative Array. See HTMLForm doc for syntax.
1348 *
1349 * @since 1.22 The 'label' attribute no longer accepts raw HTML, use 'label-raw' instead
1350 * @throws MWException
1351 */
1352 function __construct( $params ) {
1353 $this->mParams = $params;
1354
1355 # Generate the label from a message, if possible
1356 if ( isset( $params['label-message'] ) ) {
1357 $msgInfo = $params['label-message'];
1358
1359 if ( is_array( $msgInfo ) ) {
1360 $msg = array_shift( $msgInfo );
1361 } else {
1362 $msg = $msgInfo;
1363 $msgInfo = array();
1364 }
1365
1366 $this->mLabel = wfMessage( $msg, $msgInfo )->parse();
1367 } elseif ( isset( $params['label'] ) ) {
1368 if ( $params['label'] === '&#160;' ) {
1369 // Apparently some things set &nbsp directly and in an odd format
1370 $this->mLabel = '&#160;';
1371 } else {
1372 $this->mLabel = htmlspecialchars( $params['label'] );
1373 }
1374 } elseif ( isset( $params['label-raw'] ) ) {
1375 $this->mLabel = $params['label-raw'];
1376 }
1377
1378 $this->mName = "wp{$params['fieldname']}";
1379 if ( isset( $params['name'] ) ) {
1380 $this->mName = $params['name'];
1381 }
1382
1383 $validName = Sanitizer::escapeId( $this->mName );
1384 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
1385 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
1386 }
1387
1388 $this->mID = "mw-input-{$this->mName}";
1389
1390 if ( isset( $params['default'] ) ) {
1391 $this->mDefault = $params['default'];
1392 }
1393
1394 if ( isset( $params['id'] ) ) {
1395 $id = $params['id'];
1396 $validId = Sanitizer::escapeId( $id );
1397
1398 if ( $id != $validId ) {
1399 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
1400 }
1401
1402 $this->mID = $id;
1403 }
1404
1405 if ( isset( $params['cssclass'] ) ) {
1406 $this->mClass = $params['cssclass'];
1407 }
1408
1409 if ( isset( $params['validation-callback'] ) ) {
1410 $this->mValidationCallback = $params['validation-callback'];
1411 }
1412
1413 if ( isset( $params['filter-callback'] ) ) {
1414 $this->mFilterCallback = $params['filter-callback'];
1415 }
1416
1417 if ( isset( $params['flatlist'] ) ) {
1418 $this->mClass .= ' mw-htmlform-flatlist';
1419 }
1420
1421 if ( isset( $params['hidelabel'] ) ) {
1422 $this->mShowEmptyLabels = false;
1423 }
1424 }
1425
1426 /**
1427 * Get the complete table row for the input, including help text,
1428 * labels, and whatever.
1429 * @param string $value the value to set the input to.
1430 * @return String complete HTML table row.
1431 */
1432 function getTableRow( $value ) {
1433 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1434 $inputHtml = $this->getInputHTML( $value );
1435 $fieldType = get_class( $this );
1436 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1437 $cellAttributes = array();
1438
1439 if ( !empty( $this->mParams['vertical-label'] ) ) {
1440 $cellAttributes['colspan'] = 2;
1441 $verticalLabel = true;
1442 } else {
1443 $verticalLabel = false;
1444 }
1445
1446 $label = $this->getLabelHtml( $cellAttributes );
1447
1448 $field = Html::rawElement(
1449 'td',
1450 array( 'class' => 'mw-input' ) + $cellAttributes,
1451 $inputHtml . "\n$errors"
1452 );
1453
1454 if ( $verticalLabel ) {
1455 $html = Html::rawElement( 'tr',
1456 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1457 $html .= Html::rawElement( 'tr',
1458 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1459 $field );
1460 } else {
1461 $html = Html::rawElement( 'tr',
1462 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1463 $label . $field );
1464 }
1465
1466 return $html . $helptext;
1467 }
1468
1469 /**
1470 * Get the complete div for the input, including help text,
1471 * labels, and whatever.
1472 * @since 1.20
1473 * @param string $value the value to set the input to.
1474 * @return String complete HTML table row.
1475 */
1476 public function getDiv( $value ) {
1477 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1478 $inputHtml = $this->getInputHTML( $value );
1479 $fieldType = get_class( $this );
1480 $helptext = $this->getHelpTextHtmlDiv( $this->getHelpText() );
1481 $cellAttributes = array();
1482 $label = $this->getLabelHtml( $cellAttributes );
1483
1484 $outerDivClass = array(
1485 'mw-input',
1486 'mw-htmlform-nolabel' => ( $label === '' )
1487 );
1488
1489 $field = Html::rawElement(
1490 'div',
1491 array( 'class' => $outerDivClass ) + $cellAttributes,
1492 $inputHtml . "\n$errors"
1493 );
1494 $divCssClasses = array( "mw-htmlform-field-$fieldType", $this->mClass, $errorClass );
1495 if ( $this->mParent->isVForm() ) {
1496 $divCssClasses[] = 'mw-ui-vform-div';
1497 }
1498 $html = Html::rawElement( 'div',
1499 array( 'class' => $divCssClasses ),
1500 $label . $field );
1501 $html .= $helptext;
1502 return $html;
1503 }
1504
1505 /**
1506 * Get the complete raw fields for the input, including help text,
1507 * labels, and whatever.
1508 * @since 1.20
1509 * @param string $value the value to set the input to.
1510 * @return String complete HTML table row.
1511 */
1512 public function getRaw( $value ) {
1513 list( $errors, ) = $this->getErrorsAndErrorClass( $value );
1514 $inputHtml = $this->getInputHTML( $value );
1515 $helptext = $this->getHelpTextHtmlRaw( $this->getHelpText() );
1516 $cellAttributes = array();
1517 $label = $this->getLabelHtml( $cellAttributes );
1518
1519 $html = "\n$errors";
1520 $html .= $label;
1521 $html .= $inputHtml;
1522 $html .= $helptext;
1523 return $html;
1524 }
1525
1526 /**
1527 * Generate help text HTML in table format
1528 * @since 1.20
1529 * @param $helptext String|null
1530 * @return String
1531 */
1532 public function getHelpTextHtmlTable( $helptext ) {
1533 if ( is_null( $helptext ) ) {
1534 return '';
1535 }
1536
1537 $row = Html::rawElement(
1538 'td',
1539 array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
1540 $helptext
1541 );
1542 $row = Html::rawElement( 'tr', array(), $row );
1543 return $row;
1544 }
1545
1546 /**
1547 * Generate help text HTML in div format
1548 * @since 1.20
1549 * @param $helptext String|null
1550 * @return String
1551 */
1552 public function getHelpTextHtmlDiv( $helptext ) {
1553 if ( is_null( $helptext ) ) {
1554 return '';
1555 }
1556
1557 $div = Html::rawElement( 'div', array( 'class' => 'htmlform-tip' ), $helptext );
1558 return $div;
1559 }
1560
1561 /**
1562 * Generate help text HTML formatted for raw output
1563 * @since 1.20
1564 * @param $helptext String|null
1565 * @return String
1566 */
1567 public function getHelpTextHtmlRaw( $helptext ) {
1568 return $this->getHelpTextHtmlDiv( $helptext );
1569 }
1570
1571 /**
1572 * Determine the help text to display
1573 * @since 1.20
1574 * @return String
1575 */
1576 public function getHelpText() {
1577 $helptext = null;
1578
1579 if ( isset( $this->mParams['help-message'] ) ) {
1580 $this->mParams['help-messages'] = array( $this->mParams['help-message'] );
1581 }
1582
1583 if ( isset( $this->mParams['help-messages'] ) ) {
1584 foreach ( $this->mParams['help-messages'] as $name ) {
1585 $helpMessage = (array)$name;
1586 $msg = $this->msg( array_shift( $helpMessage ), $helpMessage );
1587
1588 if ( $msg->exists() ) {
1589 if ( is_null( $helptext ) ) {
1590 $helptext = '';
1591 } else {
1592 $helptext .= $this->msg( 'word-separator' )->escaped(); // some space
1593 }
1594 $helptext .= $msg->parse(); // Append message
1595 }
1596 }
1597 }
1598 elseif ( isset( $this->mParams['help'] ) ) {
1599 $helptext = $this->mParams['help'];
1600 }
1601 return $helptext;
1602 }
1603
1604 /**
1605 * Determine form errors to display and their classes
1606 * @since 1.20
1607 * @param string $value the value of the input
1608 * @return Array
1609 */
1610 public function getErrorsAndErrorClass( $value ) {
1611 $errors = $this->validate( $value, $this->mParent->mFieldData );
1612
1613 if ( $errors === true || ( !$this->mParent->getRequest()->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
1614 $errors = '';
1615 $errorClass = '';
1616 } else {
1617 $errors = self::formatErrors( $errors );
1618 $errorClass = 'mw-htmlform-invalid-input';
1619 }
1620 return array( $errors, $errorClass );
1621 }
1622
1623 function getLabel() {
1624 return is_null( $this->mLabel ) ? '' : $this->mLabel;
1625 }
1626
1627 function getLabelHtml( $cellAttributes = array() ) {
1628 # Don't output a for= attribute for labels with no associated input.
1629 # Kind of hacky here, possibly we don't want these to be <label>s at all.
1630 $for = array();
1631
1632 if ( $this->needsLabel() ) {
1633 $for['for'] = $this->mID;
1634 }
1635
1636 $labelValue = trim( $this->getLabel() );
1637 $hasLabel = false;
1638 if ( $labelValue !== '&#160;' && $labelValue !== '' ) {
1639 $hasLabel = true;
1640 }
1641
1642 $displayFormat = $this->mParent->getDisplayFormat();
1643 $html = '';
1644
1645 if ( $displayFormat === 'table' ) {
1646 $html = Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
1647 Html::rawElement( 'label', $for, $labelValue )
1648 );
1649 } elseif ( $hasLabel || $this->mShowEmptyLabels ) {
1650 if ( $displayFormat === 'div' ) {
1651 $html = Html::rawElement(
1652 'div',
1653 array( 'class' => 'mw-label' ) + $cellAttributes,
1654 Html::rawElement( 'label', $for, $labelValue )
1655 );
1656 } else {
1657 $html = Html::rawElement( 'label', $for, $labelValue );
1658 }
1659 }
1660
1661 return $html;
1662 }
1663
1664 function getDefault() {
1665 if ( isset( $this->mDefault ) ) {
1666 return $this->mDefault;
1667 } else {
1668 return null;
1669 }
1670 }
1671
1672 /**
1673 * Returns the attributes required for the tooltip and accesskey.
1674 *
1675 * @return array Attributes
1676 */
1677 public function getTooltipAndAccessKey() {
1678 if ( empty( $this->mParams['tooltip'] ) ) {
1679 return array();
1680 }
1681 return Linker::tooltipAndAccesskeyAttribs( $this->mParams['tooltip'] );
1682 }
1683
1684 /**
1685 * flatten an array of options to a single array, for instance,
1686 * a set of "<options>" inside "<optgroups>".
1687 * @param array $options Associative Array with values either Strings
1688 * or Arrays
1689 * @return Array flattened input
1690 */
1691 public static function flattenOptions( $options ) {
1692 $flatOpts = array();
1693
1694 foreach ( $options as $value ) {
1695 if ( is_array( $value ) ) {
1696 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
1697 } else {
1698 $flatOpts[] = $value;
1699 }
1700 }
1701
1702 return $flatOpts;
1703 }
1704
1705 /**
1706 * Formats one or more errors as accepted by field validation-callback.
1707 * @param $errors String|Message|Array of strings or Message instances
1708 * @return String html
1709 * @since 1.18
1710 */
1711 protected static function formatErrors( $errors ) {
1712 if ( is_array( $errors ) && count( $errors ) === 1 ) {
1713 $errors = array_shift( $errors );
1714 }
1715
1716 if ( is_array( $errors ) ) {
1717 $lines = array();
1718 foreach ( $errors as $error ) {
1719 if ( $error instanceof Message ) {
1720 $lines[] = Html::rawElement( 'li', array(), $error->parse() );
1721 } else {
1722 $lines[] = Html::rawElement( 'li', array(), $error );
1723 }
1724 }
1725 return Html::rawElement( 'ul', array( 'class' => 'error' ), implode( "\n", $lines ) );
1726 } else {
1727 if ( $errors instanceof Message ) {
1728 $errors = $errors->parse();
1729 }
1730 return Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
1731 }
1732 }
1733 }
1734
1735 class HTMLTextField extends HTMLFormField {
1736 function getSize() {
1737 return isset( $this->mParams['size'] )
1738 ? $this->mParams['size']
1739 : 45;
1740 }
1741
1742 function getInputHTML( $value ) {
1743 $attribs = array(
1744 'id' => $this->mID,
1745 'name' => $this->mName,
1746 'size' => $this->getSize(),
1747 'value' => $value,
1748 ) + $this->getTooltipAndAccessKey();
1749
1750 if ( $this->mClass !== '' ) {
1751 $attribs['class'] = $this->mClass;
1752 }
1753
1754 if ( !empty( $this->mParams['disabled'] ) ) {
1755 $attribs['disabled'] = 'disabled';
1756 }
1757
1758 # TODO: Enforce pattern, step, required, readonly on the server side as
1759 # well
1760 $allowedParams = array( 'min', 'max', 'pattern', 'title', 'step',
1761 'placeholder', 'list', 'maxlength' );
1762 foreach ( $allowedParams as $param ) {
1763 if ( isset( $this->mParams[$param] ) ) {
1764 $attribs[$param] = $this->mParams[$param];
1765 }
1766 }
1767
1768 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1769 if ( isset( $this->mParams[$param] ) ) {
1770 $attribs[$param] = '';
1771 }
1772 }
1773
1774 # Implement tiny differences between some field variants
1775 # here, rather than creating a new class for each one which
1776 # is essentially just a clone of this one.
1777 if ( isset( $this->mParams['type'] ) ) {
1778 switch ( $this->mParams['type'] ) {
1779 case 'email':
1780 $attribs['type'] = 'email';
1781 break;
1782 case 'int':
1783 $attribs['type'] = 'number';
1784 break;
1785 case 'float':
1786 $attribs['type'] = 'number';
1787 $attribs['step'] = 'any';
1788 break;
1789 # Pass through
1790 case 'password':
1791 case 'file':
1792 $attribs['type'] = $this->mParams['type'];
1793 break;
1794 }
1795 }
1796
1797 return Html::element( 'input', $attribs );
1798 }
1799 }
1800 class HTMLTextAreaField extends HTMLFormField {
1801 const DEFAULT_COLS = 80;
1802 const DEFAULT_ROWS = 25;
1803
1804 function getCols() {
1805 return isset( $this->mParams['cols'] )
1806 ? $this->mParams['cols']
1807 : static::DEFAULT_COLS;
1808 }
1809
1810 function getRows() {
1811 return isset( $this->mParams['rows'] )
1812 ? $this->mParams['rows']
1813 : static::DEFAULT_ROWS;
1814 }
1815
1816 function getInputHTML( $value ) {
1817 $attribs = array(
1818 'id' => $this->mID,
1819 'name' => $this->mName,
1820 'cols' => $this->getCols(),
1821 'rows' => $this->getRows(),
1822 ) + $this->getTooltipAndAccessKey();
1823
1824 if ( $this->mClass !== '' ) {
1825 $attribs['class'] = $this->mClass;
1826 }
1827
1828 if ( !empty( $this->mParams['disabled'] ) ) {
1829 $attribs['disabled'] = 'disabled';
1830 }
1831
1832 if ( !empty( $this->mParams['readonly'] ) ) {
1833 $attribs['readonly'] = 'readonly';
1834 }
1835
1836 if ( isset( $this->mParams['placeholder'] ) ) {
1837 $attribs['placeholder'] = $this->mParams['placeholder'];
1838 }
1839
1840 foreach ( array( 'required', 'autofocus' ) as $param ) {
1841 if ( isset( $this->mParams[$param] ) ) {
1842 $attribs[$param] = '';
1843 }
1844 }
1845
1846 return Html::element( 'textarea', $attribs, $value );
1847 }
1848 }
1849
1850 /**
1851 * A field that will contain a numeric value
1852 */
1853 class HTMLFloatField extends HTMLTextField {
1854 function getSize() {
1855 return isset( $this->mParams['size'] )
1856 ? $this->mParams['size']
1857 : 20;
1858 }
1859
1860 function validate( $value, $alldata ) {
1861 $p = parent::validate( $value, $alldata );
1862
1863 if ( $p !== true ) {
1864 return $p;
1865 }
1866
1867 $value = trim( $value );
1868
1869 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1870 # with the addition that a leading '+' sign is ok.
1871 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1872 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1873 }
1874
1875 # The "int" part of these message names is rather confusing.
1876 # They make equal sense for all numbers.
1877 if ( isset( $this->mParams['min'] ) ) {
1878 $min = $this->mParams['min'];
1879
1880 if ( $min > $value ) {
1881 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1882 }
1883 }
1884
1885 if ( isset( $this->mParams['max'] ) ) {
1886 $max = $this->mParams['max'];
1887
1888 if ( $max < $value ) {
1889 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1890 }
1891 }
1892
1893 return true;
1894 }
1895 }
1896
1897 /**
1898 * A field that must contain a number
1899 */
1900 class HTMLIntField extends HTMLFloatField {
1901 function validate( $value, $alldata ) {
1902 $p = parent::validate( $value, $alldata );
1903
1904 if ( $p !== true ) {
1905 return $p;
1906 }
1907
1908 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1909 # with the addition that a leading '+' sign is ok. Note that leading zeros
1910 # are fine, and will be left in the input, which is useful for things like
1911 # phone numbers when you know that they are integers (the HTML5 type=tel
1912 # input does not require its value to be numeric). If you want a tidier
1913 # value to, eg, save in the DB, clean it up with intval().
1914 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1915 ) {
1916 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1917 }
1918
1919 return true;
1920 }
1921 }
1922
1923 /**
1924 * A checkbox field
1925 */
1926 class HTMLCheckField extends HTMLFormField {
1927 function getInputHTML( $value ) {
1928 if ( !empty( $this->mParams['invert'] ) ) {
1929 $value = !$value;
1930 }
1931
1932 $attr = $this->getTooltipAndAccessKey();
1933 $attr['id'] = $this->mID;
1934
1935 if ( !empty( $this->mParams['disabled'] ) ) {
1936 $attr['disabled'] = 'disabled';
1937 }
1938
1939 if ( $this->mClass !== '' ) {
1940 $attr['class'] = $this->mClass;
1941 }
1942
1943 if ( $this->mParent->isVForm() ) {
1944 // Nest checkbox inside label.
1945 return Html::rawElement(
1946 'label',
1947 array(
1948 'class' => 'mw-ui-checkbox-label'
1949 ),
1950 Xml::check(
1951 $this->mName,
1952 $value,
1953 $attr
1954 ) .
1955 // Html:rawElement doesn't escape contents.
1956 htmlspecialchars( $this->mLabel )
1957 );
1958 } else {
1959 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1960 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1961 }
1962 }
1963
1964 /**
1965 * For a checkbox, the label goes on the right hand side, and is
1966 * added in getInputHTML(), rather than HTMLFormField::getRow()
1967 * @return String
1968 */
1969 function getLabel() {
1970 return '&#160;';
1971 }
1972
1973 /**
1974 * checkboxes don't need a label.
1975 */
1976 protected function needsLabel() {
1977 return false;
1978 }
1979
1980 /**
1981 * @param $request WebRequest
1982 * @return String
1983 */
1984 function loadDataFromRequest( $request ) {
1985 $invert = false;
1986 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1987 $invert = true;
1988 }
1989
1990 // GetCheck won't work like we want for checks.
1991 // Fetch the value in either one of the two following case:
1992 // - we have a valid token (form got posted or GET forged by the user)
1993 // - checkbox name has a value (false or true), ie is not null
1994 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1995 // XOR has the following truth table, which is what we want
1996 // INVERT VALUE | OUTPUT
1997 // true true | false
1998 // false true | true
1999 // false false | false
2000 // true false | true
2001 return $request->getBool( $this->mName ) xor $invert;
2002 } else {
2003 return $this->getDefault();
2004 }
2005 }
2006 }
2007
2008 /**
2009 * A checkbox matrix
2010 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
2011 * options, uses an array of rows and an array of columns to dynamically
2012 * construct a matrix of options. The tags used to identify a particular cell
2013 * are of the form "columnName-rowName"
2014 *
2015 * Options:
2016 * - columns
2017 * - Required list of columns in the matrix.
2018 * - rows
2019 * - Required list of rows in the matrix.
2020 * - force-options-on
2021 * - Accepts array of column-row tags to be displayed as enabled but unavailable to change
2022 * - force-options-off
2023 * - Accepts array of column-row tags to be displayed as disabled but unavailable to change.
2024 * - tooltips
2025 * - Optional array mapping row label to tooltip content
2026 * - tooltip-class
2027 * - Optional CSS class used on tooltip container span. Defaults to mw-icon-question.
2028 */
2029 class HTMLCheckMatrix extends HTMLFormField implements HTMLNestedFilterable {
2030
2031 static private $requiredParams = array(
2032 // Required by underlying HTMLFormField
2033 'fieldname',
2034 // Required by HTMLCheckMatrix
2035 'rows', 'columns'
2036 );
2037
2038 public function __construct( $params ) {
2039 $missing = array_diff( self::$requiredParams, array_keys( $params ) );
2040 if ( $missing ) {
2041 throw new HTMLFormFieldRequiredOptionsException( $this, $missing );
2042 }
2043 parent::__construct( $params );
2044 }
2045
2046 function validate( $value, $alldata ) {
2047 $rows = $this->mParams['rows'];
2048 $columns = $this->mParams['columns'];
2049
2050 // Make sure user-defined validation callback is run
2051 $p = parent::validate( $value, $alldata );
2052 if ( $p !== true ) {
2053 return $p;
2054 }
2055
2056 // Make sure submitted value is an array
2057 if ( !is_array( $value ) ) {
2058 return false;
2059 }
2060
2061 // If all options are valid, array_intersect of the valid options
2062 // and the provided options will return the provided options.
2063 $validOptions = array();
2064 foreach ( $rows as $rowTag ) {
2065 foreach ( $columns as $columnTag ) {
2066 $validOptions[] = $columnTag . '-' . $rowTag;
2067 }
2068 }
2069 $validValues = array_intersect( $value, $validOptions );
2070 if ( count( $validValues ) == count( $value ) ) {
2071 return true;
2072 } else {
2073 return $this->msg( 'htmlform-select-badoption' )->parse();
2074 }
2075 }
2076
2077 /**
2078 * Build a table containing a matrix of checkbox options.
2079 * The value of each option is a combination of the row tag and column tag.
2080 * mParams['rows'] is an array with row labels as keys and row tags as values.
2081 * mParams['columns'] is an array with column labels as keys and column tags as values.
2082 * @param array $value of the options that should be checked
2083 * @return String
2084 */
2085 function getInputHTML( $value ) {
2086 $html = '';
2087 $tableContents = '';
2088 $attribs = array();
2089 $rows = $this->mParams['rows'];
2090 $columns = $this->mParams['columns'];
2091
2092 // If the disabled param is set, disable all the options
2093 if ( !empty( $this->mParams['disabled'] ) ) {
2094 $attribs['disabled'] = 'disabled';
2095 }
2096
2097 // Build the column headers
2098 $headerContents = Html::rawElement( 'td', array(), '&#160;' );
2099 foreach ( $columns as $columnLabel => $columnTag ) {
2100 $headerContents .= Html::rawElement( 'td', array(), $columnLabel );
2101 }
2102 $tableContents .= Html::rawElement( 'tr', array(), "\n$headerContents\n" );
2103
2104 $tooltipClass = 'mw-icon-question';
2105 if ( isset( $this->mParams['tooltip-class'] ) ) {
2106 $tooltipClass = $this->mParams['tooltip-class'];
2107 }
2108
2109 // Build the options matrix
2110 foreach ( $rows as $rowLabel => $rowTag ) {
2111 // Append tooltip if configured
2112 if ( isset( $this->mParams['tooltips'][$rowLabel] ) ) {
2113 $tooltipAttribs = array(
2114 'class' => "mw-htmlform-tooltip $tooltipClass",
2115 'title' => $this->mParams['tooltips'][$rowLabel],
2116 );
2117 $rowLabel .= ' ' . Html::element( 'span', $tooltipAttribs, '' );
2118 }
2119 $rowContents = Html::rawElement( 'td', array(), $rowLabel );
2120 foreach ( $columns as $columnTag ) {
2121 $thisTag = "$columnTag-$rowTag";
2122 // Construct the checkbox
2123 $thisAttribs = array(
2124 'id' => "{$this->mID}-$thisTag",
2125 'value' => $thisTag,
2126 );
2127 $checked = in_array( $thisTag, (array)$value, true );
2128 if ( $this->isTagForcedOff( $thisTag ) ) {
2129 $checked = false;
2130 $thisAttribs['disabled'] = 1;
2131 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2132 $checked = true;
2133 $thisAttribs['disabled'] = 1;
2134 }
2135 $rowContents .= Html::rawElement(
2136 'td',
2137 array(),
2138 Xml::check( "{$this->mName}[]", $checked, $attribs + $thisAttribs )
2139 );
2140 }
2141 $tableContents .= Html::rawElement( 'tr', array(), "\n$rowContents\n" );
2142 }
2143
2144 // Put it all in a table
2145 $html .= Html::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
2146 Html::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
2147
2148 return $html;
2149 }
2150
2151 protected function isTagForcedOff( $tag ) {
2152 return isset( $this->mParams['force-options-off'] )
2153 && in_array( $tag, $this->mParams['force-options-off'] );
2154 }
2155
2156 protected function isTagForcedOn( $tag ) {
2157 return isset( $this->mParams['force-options-on'] )
2158 && in_array( $tag, $this->mParams['force-options-on'] );
2159 }
2160
2161 /**
2162 * Get the complete table row for the input, including help text,
2163 * labels, and whatever.
2164 * We override this function since the label should always be on a separate
2165 * line above the options in the case of a checkbox matrix, i.e. it's always
2166 * a "vertical-label".
2167 * @param string $value the value to set the input to
2168 * @return String complete HTML table row
2169 */
2170 function getTableRow( $value ) {
2171 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
2172 $inputHtml = $this->getInputHTML( $value );
2173 $fieldType = get_class( $this );
2174 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
2175 $cellAttributes = array( 'colspan' => 2 );
2176
2177 $label = $this->getLabelHtml( $cellAttributes );
2178
2179 $field = Html::rawElement(
2180 'td',
2181 array( 'class' => 'mw-input' ) + $cellAttributes,
2182 $inputHtml . "\n$errors"
2183 );
2184
2185 $html = Html::rawElement( 'tr',
2186 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
2187 $html .= Html::rawElement( 'tr',
2188 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
2189 $field );
2190
2191 return $html . $helptext;
2192 }
2193
2194 /**
2195 * @param $request WebRequest
2196 * @return Array
2197 */
2198 function loadDataFromRequest( $request ) {
2199 if ( $this->mParent->getMethod() == 'post' ) {
2200 if ( $request->wasPosted() ) {
2201 // Checkboxes are not added to the request arrays if they're not checked,
2202 // so it's perfectly possible for there not to be an entry at all
2203 return $request->getArray( $this->mName, array() );
2204 } else {
2205 // That's ok, the user has not yet submitted the form, so show the defaults
2206 return $this->getDefault();
2207 }
2208 } else {
2209 // This is the impossible case: if we look at $_GET and see no data for our
2210 // field, is it because the user has not yet submitted the form, or that they
2211 // have submitted it with all the options unchecked. We will have to assume the
2212 // latter, which basically means that you can't specify 'positive' defaults
2213 // for GET forms.
2214 return $request->getArray( $this->mName, array() );
2215 }
2216 }
2217
2218 function getDefault() {
2219 if ( isset( $this->mDefault ) ) {
2220 return $this->mDefault;
2221 } else {
2222 return array();
2223 }
2224 }
2225
2226 function filterDataForSubmit( $data ) {
2227 $columns = HTMLFormField::flattenOptions( $this->mParams['columns'] );
2228 $rows = HTMLFormField::flattenOptions( $this->mParams['rows'] );
2229 $res = array();
2230 foreach ( $columns as $column ) {
2231 foreach ( $rows as $row ) {
2232 // Make sure option hasn't been forced
2233 $thisTag = "$column-$row";
2234 if ( $this->isTagForcedOff( $thisTag ) ) {
2235 $res[$thisTag] = false;
2236 } elseif ( $this->isTagForcedOn( $thisTag ) ) {
2237 $res[$thisTag] = true;
2238 } else {
2239 $res[$thisTag] = in_array( $thisTag, $data );
2240 }
2241 }
2242 }
2243
2244 return $res;
2245 }
2246 }
2247
2248 /**
2249 * A select dropdown field. Basically a wrapper for Xmlselect class
2250 */
2251 class HTMLSelectField extends HTMLFormField {
2252 function validate( $value, $alldata ) {
2253 $p = parent::validate( $value, $alldata );
2254
2255 if ( $p !== true ) {
2256 return $p;
2257 }
2258
2259 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2260
2261 if ( in_array( $value, $validOptions ) ) {
2262 return true;
2263 } else {
2264 return $this->msg( 'htmlform-select-badoption' )->parse();
2265 }
2266 }
2267
2268 function getInputHTML( $value ) {
2269 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
2270
2271 # If one of the options' 'name' is int(0), it is automatically selected.
2272 # because PHP sucks and thinks int(0) == 'some string'.
2273 # Working around this by forcing all of them to strings.
2274 foreach ( $this->mParams['options'] as &$opt ) {
2275 if ( is_int( $opt ) ) {
2276 $opt = strval( $opt );
2277 }
2278 }
2279 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2280
2281 if ( !empty( $this->mParams['disabled'] ) ) {
2282 $select->setAttribute( 'disabled', 'disabled' );
2283 }
2284
2285 if ( $this->mClass !== '' ) {
2286 $select->setAttribute( 'class', $this->mClass );
2287 }
2288
2289 $select->addOptions( $this->mParams['options'] );
2290
2291 return $select->getHTML();
2292 }
2293 }
2294
2295 /**
2296 * Select dropdown field, with an additional "other" textbox.
2297 */
2298 class HTMLSelectOrOtherField extends HTMLTextField {
2299
2300 function __construct( $params ) {
2301 if ( !in_array( 'other', $params['options'], true ) ) {
2302 $msg = isset( $params['other'] ) ?
2303 $params['other'] :
2304 wfMessage( 'htmlform-selectorother-other' )->text();
2305 $params['options'][$msg] = 'other';
2306 }
2307
2308 parent::__construct( $params );
2309 }
2310
2311 static function forceToStringRecursive( $array ) {
2312 if ( is_array( $array ) ) {
2313 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
2314 } else {
2315 return strval( $array );
2316 }
2317 }
2318
2319 function getInputHTML( $value ) {
2320 $valInSelect = false;
2321
2322 if ( $value !== false ) {
2323 $valInSelect = in_array(
2324 $value,
2325 HTMLFormField::flattenOptions( $this->mParams['options'] )
2326 );
2327 }
2328
2329 $selected = $valInSelect ? $value : 'other';
2330
2331 $opts = self::forceToStringRecursive( $this->mParams['options'] );
2332
2333 $select = new XmlSelect( $this->mName, $this->mID, $selected );
2334 $select->addOptions( $opts );
2335
2336 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2337
2338 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
2339
2340 if ( !empty( $this->mParams['disabled'] ) ) {
2341 $select->setAttribute( 'disabled', 'disabled' );
2342 $tbAttribs['disabled'] = 'disabled';
2343 }
2344
2345 $select = $select->getHTML();
2346
2347 if ( isset( $this->mParams['maxlength'] ) ) {
2348 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
2349 }
2350
2351 if ( $this->mClass !== '' ) {
2352 $tbAttribs['class'] = $this->mClass;
2353 }
2354
2355 $textbox = Html::input(
2356 $this->mName . '-other',
2357 $valInSelect ? '' : $value,
2358 'text',
2359 $tbAttribs
2360 );
2361
2362 return "$select<br />\n$textbox";
2363 }
2364
2365 /**
2366 * @param $request WebRequest
2367 * @return String
2368 */
2369 function loadDataFromRequest( $request ) {
2370 if ( $request->getCheck( $this->mName ) ) {
2371 $val = $request->getText( $this->mName );
2372
2373 if ( $val == 'other' ) {
2374 $val = $request->getText( $this->mName . '-other' );
2375 }
2376
2377 return $val;
2378 } else {
2379 return $this->getDefault();
2380 }
2381 }
2382 }
2383
2384 /**
2385 * Multi-select field
2386 */
2387 class HTMLMultiSelectField extends HTMLFormField implements HTMLNestedFilterable {
2388
2389 function validate( $value, $alldata ) {
2390 $p = parent::validate( $value, $alldata );
2391
2392 if ( $p !== true ) {
2393 return $p;
2394 }
2395
2396 if ( !is_array( $value ) ) {
2397 return false;
2398 }
2399
2400 # If all options are valid, array_intersect of the valid options
2401 # and the provided options will return the provided options.
2402 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2403
2404 $validValues = array_intersect( $value, $validOptions );
2405 if ( count( $validValues ) == count( $value ) ) {
2406 return true;
2407 } else {
2408 return $this->msg( 'htmlform-select-badoption' )->parse();
2409 }
2410 }
2411
2412 function getInputHTML( $value ) {
2413 $html = $this->formatOptions( $this->mParams['options'], $value );
2414
2415 return $html;
2416 }
2417
2418 function formatOptions( $options, $value ) {
2419 $html = '';
2420
2421 $attribs = array();
2422
2423 if ( !empty( $this->mParams['disabled'] ) ) {
2424 $attribs['disabled'] = 'disabled';
2425 }
2426
2427 foreach ( $options as $label => $info ) {
2428 if ( is_array( $info ) ) {
2429 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2430 $html .= $this->formatOptions( $info, $value );
2431 } else {
2432 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2433
2434 $checkbox = Xml::check(
2435 $this->mName . '[]',
2436 in_array( $info, $value, true ),
2437 $attribs + $thisAttribs );
2438 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2439
2440 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2441 }
2442 }
2443
2444 return $html;
2445 }
2446
2447 /**
2448 * @param $request WebRequest
2449 * @return String
2450 */
2451 function loadDataFromRequest( $request ) {
2452 if ( $this->mParent->getMethod() == 'post' ) {
2453 if ( $request->wasPosted() ) {
2454 # Checkboxes are just not added to the request arrays if they're not checked,
2455 # so it's perfectly possible for there not to be an entry at all
2456 return $request->getArray( $this->mName, array() );
2457 } else {
2458 # That's ok, the user has not yet submitted the form, so show the defaults
2459 return $this->getDefault();
2460 }
2461 } else {
2462 # This is the impossible case: if we look at $_GET and see no data for our
2463 # field, is it because the user has not yet submitted the form, or that they
2464 # have submitted it with all the options unchecked? We will have to assume the
2465 # latter, which basically means that you can't specify 'positive' defaults
2466 # for GET forms.
2467 # @todo FIXME...
2468 return $request->getArray( $this->mName, array() );
2469 }
2470 }
2471
2472 function getDefault() {
2473 if ( isset( $this->mDefault ) ) {
2474 return $this->mDefault;
2475 } else {
2476 return array();
2477 }
2478 }
2479
2480 function filterDataForSubmit( $data ) {
2481 $options = HTMLFormField::flattenOptions( $this->mParams['options'] );
2482
2483 $res = array();
2484 foreach ( $options as $opt ) {
2485 $res["$opt"] = in_array( $opt, $data );
2486 }
2487
2488 return $res;
2489 }
2490
2491 protected function needsLabel() {
2492 return false;
2493 }
2494 }
2495
2496 /**
2497 * Double field with a dropdown list constructed from a system message in the format
2498 * * Optgroup header
2499 * ** <option value>
2500 * * New Optgroup header
2501 * Plus a text field underneath for an additional reason. The 'value' of the field is
2502 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2503 * select dropdown.
2504 * @todo FIXME: If made 'required', only the text field should be compulsory.
2505 */
2506 class HTMLSelectAndOtherField extends HTMLSelectField {
2507
2508 function __construct( $params ) {
2509 if ( array_key_exists( 'other', $params ) ) {
2510 } elseif ( array_key_exists( 'other-message', $params ) ) {
2511 $params['other'] = wfMessage( $params['other-message'] )->plain();
2512 } else {
2513 $params['other'] = null;
2514 }
2515
2516 if ( array_key_exists( 'options', $params ) ) {
2517 # Options array already specified
2518 } elseif ( array_key_exists( 'options-message', $params ) ) {
2519 # Generate options array from a system message
2520 $params['options'] = self::parseMessage(
2521 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2522 $params['other']
2523 );
2524 } else {
2525 # Sulk
2526 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2527 }
2528 $this->mFlatOptions = self::flattenOptions( $params['options'] );
2529
2530 parent::__construct( $params );
2531 }
2532
2533 /**
2534 * Build a drop-down box from a textual list.
2535 * @param string $string message text
2536 * @param string $otherName name of "other reason" option
2537 * @return Array
2538 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2539 */
2540 public static function parseMessage( $string, $otherName = null ) {
2541 if ( $otherName === null ) {
2542 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2543 }
2544
2545 $optgroup = false;
2546 $options = array( $otherName => 'other' );
2547
2548 foreach ( explode( "\n", $string ) as $option ) {
2549 $value = trim( $option );
2550 if ( $value == '' ) {
2551 continue;
2552 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2553 # A new group is starting...
2554 $value = trim( substr( $value, 1 ) );
2555 $optgroup = $value;
2556 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2557 # groupmember
2558 $opt = trim( substr( $value, 2 ) );
2559 if ( $optgroup === false ) {
2560 $options[$opt] = $opt;
2561 } else {
2562 $options[$optgroup][$opt] = $opt;
2563 }
2564 } else {
2565 # groupless reason list
2566 $optgroup = false;
2567 $options[$option] = $option;
2568 }
2569 }
2570
2571 return $options;
2572 }
2573
2574 function getInputHTML( $value ) {
2575 $select = parent::getInputHTML( $value[1] );
2576
2577 $textAttribs = array(
2578 'id' => $this->mID . '-other',
2579 'size' => $this->getSize(),
2580 );
2581
2582 if ( $this->mClass !== '' ) {
2583 $textAttribs['class'] = $this->mClass;
2584 }
2585
2586 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2587 if ( isset( $this->mParams[$param] ) ) {
2588 $textAttribs[$param] = '';
2589 }
2590 }
2591
2592 $textbox = Html::input(
2593 $this->mName . '-other',
2594 $value[2],
2595 'text',
2596 $textAttribs
2597 );
2598
2599 return "$select<br />\n$textbox";
2600 }
2601
2602 /**
2603 * @param $request WebRequest
2604 * @return Array("<overall message>","<select value>","<text field value>")
2605 */
2606 function loadDataFromRequest( $request ) {
2607 if ( $request->getCheck( $this->mName ) ) {
2608
2609 $list = $request->getText( $this->mName );
2610 $text = $request->getText( $this->mName . '-other' );
2611
2612 if ( $list == 'other' ) {
2613 $final = $text;
2614 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2615 # User has spoofed the select form to give an option which wasn't
2616 # in the original offer. Sulk...
2617 $final = $text;
2618 } elseif ( $text == '' ) {
2619 $final = $list;
2620 } else {
2621 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2622 }
2623
2624 } else {
2625 $final = $this->getDefault();
2626
2627 $list = 'other';
2628 $text = $final;
2629 foreach ( $this->mFlatOptions as $option ) {
2630 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2631 if ( strpos( $text, $match ) === 0 ) {
2632 $list = $option;
2633 $text = substr( $text, strlen( $match ) );
2634 break;
2635 }
2636 }
2637 }
2638 return array( $final, $list, $text );
2639 }
2640
2641 function getSize() {
2642 return isset( $this->mParams['size'] )
2643 ? $this->mParams['size']
2644 : 45;
2645 }
2646
2647 function validate( $value, $alldata ) {
2648 # HTMLSelectField forces $value to be one of the options in the select
2649 # field, which is not useful here. But we do want the validation further up
2650 # the chain
2651 $p = parent::validate( $value[1], $alldata );
2652
2653 if ( $p !== true ) {
2654 return $p;
2655 }
2656
2657 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value[1] === '' ) {
2658 return $this->msg( 'htmlform-required' )->parse();
2659 }
2660
2661 return true;
2662 }
2663 }
2664
2665 /**
2666 * Radio checkbox fields.
2667 */
2668 class HTMLRadioField extends HTMLFormField {
2669
2670 function validate( $value, $alldata ) {
2671 $p = parent::validate( $value, $alldata );
2672
2673 if ( $p !== true ) {
2674 return $p;
2675 }
2676
2677 if ( !is_string( $value ) && !is_int( $value ) ) {
2678 return false;
2679 }
2680
2681 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2682
2683 if ( in_array( $value, $validOptions ) ) {
2684 return true;
2685 } else {
2686 return $this->msg( 'htmlform-select-badoption' )->parse();
2687 }
2688 }
2689
2690 /**
2691 * This returns a block of all the radio options, in one cell.
2692 * @see includes/HTMLFormField#getInputHTML()
2693 * @param $value String
2694 * @return String
2695 */
2696 function getInputHTML( $value ) {
2697 $html = $this->formatOptions( $this->mParams['options'], $value );
2698
2699 return $html;
2700 }
2701
2702 function formatOptions( $options, $value ) {
2703 $html = '';
2704
2705 $attribs = array();
2706 if ( !empty( $this->mParams['disabled'] ) ) {
2707 $attribs['disabled'] = 'disabled';
2708 }
2709
2710 # TODO: should this produce an unordered list perhaps?
2711 foreach ( $options as $label => $info ) {
2712 if ( is_array( $info ) ) {
2713 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2714 $html .= $this->formatOptions( $info, $value );
2715 } else {
2716 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2717 $radio = Xml::radio(
2718 $this->mName,
2719 $info,
2720 $info == $value,
2721 $attribs + array( 'id' => $id )
2722 );
2723 $radio .= '&#160;' .
2724 Html::rawElement( 'label', array( 'for' => $id ), $label );
2725
2726 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2727 }
2728 }
2729
2730 return $html;
2731 }
2732
2733 protected function needsLabel() {
2734 return false;
2735 }
2736 }
2737
2738 /**
2739 * An information field (text blob), not a proper input.
2740 */
2741 class HTMLInfoField extends HTMLFormField {
2742 public function __construct( $info ) {
2743 $info['nodata'] = true;
2744
2745 parent::__construct( $info );
2746 }
2747
2748 public function getInputHTML( $value ) {
2749 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2750 }
2751
2752 public function getTableRow( $value ) {
2753 if ( !empty( $this->mParams['rawrow'] ) ) {
2754 return $value;
2755 }
2756
2757 return parent::getTableRow( $value );
2758 }
2759
2760 /**
2761 * @since 1.20
2762 */
2763 public function getDiv( $value ) {
2764 if ( !empty( $this->mParams['rawrow'] ) ) {
2765 return $value;
2766 }
2767
2768 return parent::getDiv( $value );
2769 }
2770
2771 /**
2772 * @since 1.20
2773 */
2774 public function getRaw( $value ) {
2775 if ( !empty( $this->mParams['rawrow'] ) ) {
2776 return $value;
2777 }
2778
2779 return parent::getRaw( $value );
2780 }
2781
2782 protected function needsLabel() {
2783 return false;
2784 }
2785 }
2786
2787 class HTMLHiddenField extends HTMLFormField {
2788 public function __construct( $params ) {
2789 parent::__construct( $params );
2790
2791 # Per HTML5 spec, hidden fields cannot be 'required'
2792 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2793 unset( $this->mParams['required'] );
2794 }
2795
2796 public function getTableRow( $value ) {
2797 $params = array();
2798 if ( $this->mID ) {
2799 $params['id'] = $this->mID;
2800 }
2801
2802 $this->mParent->addHiddenField(
2803 $this->mName,
2804 $this->mDefault,
2805 $params
2806 );
2807
2808 return '';
2809 }
2810
2811 /**
2812 * @since 1.20
2813 */
2814 public function getDiv( $value ) {
2815 return $this->getTableRow( $value );
2816 }
2817
2818 /**
2819 * @since 1.20
2820 */
2821 public function getRaw( $value ) {
2822 return $this->getTableRow( $value );
2823 }
2824
2825 public function getInputHTML( $value ) {
2826 return '';
2827 }
2828 }
2829
2830 /**
2831 * Add a submit button inline in the form (as opposed to
2832 * HTMLForm::addButton(), which will add it at the end).
2833 */
2834 class HTMLSubmitField extends HTMLButtonField {
2835 protected $buttonType = 'submit';
2836 }
2837
2838 /**
2839 * Adds a generic button inline to the form. Does not do anything, you must add
2840 * click handling code in JavaScript. Use a HTMLSubmitField if you merely
2841 * wish to add a submit button to a form.
2842 *
2843 * @since 1.22
2844 */
2845 class HTMLButtonField extends HTMLFormField {
2846 protected $buttonType = 'button';
2847
2848 public function __construct( $info ) {
2849 $info['nodata'] = true;
2850 parent::__construct( $info );
2851 }
2852
2853 public function getInputHTML( $value ) {
2854 $attr = array(
2855 'class' => 'mw-htmlform-submit ' . $this->mClass,
2856 'id' => $this->mID,
2857 );
2858
2859 if ( !empty( $this->mParams['disabled'] ) ) {
2860 $attr['disabled'] = 'disabled';
2861 }
2862
2863 return Html::input(
2864 $this->mName,
2865 $value,
2866 $this->buttonType,
2867 $attr
2868 );
2869 }
2870
2871 protected function needsLabel() {
2872 return false;
2873 }
2874
2875 /**
2876 * Button cannot be invalid
2877 * @param $value String
2878 * @param $alldata Array
2879 * @return Bool
2880 */
2881 public function validate( $value, $alldata ) {
2882 return true;
2883 }
2884 }
2885
2886 class HTMLEditTools extends HTMLFormField {
2887 public function getInputHTML( $value ) {
2888 return '';
2889 }
2890
2891 public function getTableRow( $value ) {
2892 $msg = $this->formatMsg();
2893
2894 return '<tr><td></td><td class="mw-input">'
2895 . '<div class="mw-editTools">'
2896 . $msg->parseAsBlock()
2897 . "</div></td></tr>\n";
2898 }
2899
2900 /**
2901 * @since 1.20
2902 */
2903 public function getDiv( $value ) {
2904 $msg = $this->formatMsg();
2905 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2906 }
2907
2908 /**
2909 * @since 1.20
2910 */
2911 public function getRaw( $value ) {
2912 return $this->getDiv( $value );
2913 }
2914
2915 protected function formatMsg() {
2916 if ( empty( $this->mParams['message'] ) ) {
2917 $msg = $this->msg( 'edittools' );
2918 } else {
2919 $msg = $this->msg( $this->mParams['message'] );
2920 if ( $msg->isDisabled() ) {
2921 $msg = $this->msg( 'edittools' );
2922 }
2923 }
2924 $msg->inContentLanguage();
2925 return $msg;
2926 }
2927 }
2928
2929 class HTMLApiField extends HTMLFormField {
2930 public function getTableRow( $value ) {
2931 return '';
2932 }
2933
2934 public function getDiv( $value ) {
2935 return $this->getTableRow( $value );
2936 }
2937
2938 public function getRaw( $value ) {
2939 return $this->getTableRow( $value );
2940 }
2941
2942 public function getInputHTML( $value ) {
2943 return '';
2944 }
2945 }
2946
2947 interface HTMLNestedFilterable {
2948 /**
2949 * Support for seperating multi-option preferences into multiple preferences
2950 * Due to lack of array support.
2951 * @param $data array
2952 */
2953 function filterDataForSubmit( $data );
2954 }
2955
2956 class HTMLFormFieldRequiredOptionsException extends MWException {
2957 public function __construct( HTMLFormField $field, array $missing ) {
2958 parent::__construct( sprintf(
2959 "Form type `%s` expected the following parameters to be set: %s",
2960 get_class( $field ),
2961 implode( ', ', $missing )
2962 ) );
2963 }
2964 }