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