1d9a3d0a8244a476cead85c692c0a46bb5020d98
[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 const DEFAULT_COLS = 80;
1627 const DEFAULT_ROWS = 25;
1628
1629 function getCols() {
1630 return isset( $this->mParams['cols'] )
1631 ? $this->mParams['cols']
1632 : static::DEFAULT_COLS;
1633 }
1634
1635 function getRows() {
1636 return isset( $this->mParams['rows'] )
1637 ? $this->mParams['rows']
1638 : static::DEFAULT_ROWS;
1639 }
1640
1641 function getInputHTML( $value ) {
1642 $attribs = array(
1643 'id' => $this->mID,
1644 'name' => $this->mName,
1645 'cols' => $this->getCols(),
1646 'rows' => $this->getRows(),
1647 ) + $this->getTooltipAndAccessKey();
1648
1649 if ( $this->mClass !== '' ) {
1650 $attribs['class'] = $this->mClass;
1651 }
1652
1653 if ( !empty( $this->mParams['disabled'] ) ) {
1654 $attribs['disabled'] = 'disabled';
1655 }
1656
1657 if ( !empty( $this->mParams['readonly'] ) ) {
1658 $attribs['readonly'] = 'readonly';
1659 }
1660
1661 if ( isset( $this->mParams['placeholder'] ) ) {
1662 $attribs['placeholder'] = $this->mParams['placeholder'];
1663 }
1664
1665 foreach ( array( 'required', 'autofocus' ) as $param ) {
1666 if ( isset( $this->mParams[$param] ) ) {
1667 $attribs[$param] = '';
1668 }
1669 }
1670
1671 return Html::element( 'textarea', $attribs, $value );
1672 }
1673 }
1674
1675 /**
1676 * A field that will contain a numeric value
1677 */
1678 class HTMLFloatField extends HTMLTextField {
1679 function getSize() {
1680 return isset( $this->mParams['size'] )
1681 ? $this->mParams['size']
1682 : 20;
1683 }
1684
1685 function validate( $value, $alldata ) {
1686 $p = parent::validate( $value, $alldata );
1687
1688 if ( $p !== true ) {
1689 return $p;
1690 }
1691
1692 $value = trim( $value );
1693
1694 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1695 # with the addition that a leading '+' sign is ok.
1696 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1697 return $this->msg( 'htmlform-float-invalid' )->parseAsBlock();
1698 }
1699
1700 # The "int" part of these message names is rather confusing.
1701 # They make equal sense for all numbers.
1702 if ( isset( $this->mParams['min'] ) ) {
1703 $min = $this->mParams['min'];
1704
1705 if ( $min > $value ) {
1706 return $this->msg( 'htmlform-int-toolow', $min )->parseAsBlock();
1707 }
1708 }
1709
1710 if ( isset( $this->mParams['max'] ) ) {
1711 $max = $this->mParams['max'];
1712
1713 if ( $max < $value ) {
1714 return $this->msg( 'htmlform-int-toohigh', $max )->parseAsBlock();
1715 }
1716 }
1717
1718 return true;
1719 }
1720 }
1721
1722 /**
1723 * A field that must contain a number
1724 */
1725 class HTMLIntField extends HTMLFloatField {
1726 function validate( $value, $alldata ) {
1727 $p = parent::validate( $value, $alldata );
1728
1729 if ( $p !== true ) {
1730 return $p;
1731 }
1732
1733 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1734 # with the addition that a leading '+' sign is ok. Note that leading zeros
1735 # are fine, and will be left in the input, which is useful for things like
1736 # phone numbers when you know that they are integers (the HTML5 type=tel
1737 # input does not require its value to be numeric). If you want a tidier
1738 # value to, eg, save in the DB, clean it up with intval().
1739 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1740 ) {
1741 return $this->msg( 'htmlform-int-invalid' )->parseAsBlock();
1742 }
1743
1744 return true;
1745 }
1746 }
1747
1748 /**
1749 * A checkbox field
1750 */
1751 class HTMLCheckField extends HTMLFormField {
1752 function getInputHTML( $value ) {
1753 if ( !empty( $this->mParams['invert'] ) ) {
1754 $value = !$value;
1755 }
1756
1757 $attr = $this->getTooltipAndAccessKey();
1758 $attr['id'] = $this->mID;
1759
1760 if ( !empty( $this->mParams['disabled'] ) ) {
1761 $attr['disabled'] = 'disabled';
1762 }
1763
1764 if ( $this->mClass !== '' ) {
1765 $attr['class'] = $this->mClass;
1766 }
1767
1768 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1769 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1770 }
1771
1772 /**
1773 * For a checkbox, the label goes on the right hand side, and is
1774 * added in getInputHTML(), rather than HTMLFormField::getRow()
1775 * @return String
1776 */
1777 function getLabel() {
1778 return '&#160;';
1779 }
1780
1781 /**
1782 * @param $request WebRequest
1783 * @return String
1784 */
1785 function loadDataFromRequest( $request ) {
1786 $invert = false;
1787 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1788 $invert = true;
1789 }
1790
1791 // GetCheck won't work like we want for checks.
1792 // Fetch the value in either one of the two following case:
1793 // - we have a valid token (form got posted or GET forged by the user)
1794 // - checkbox name has a value (false or true), ie is not null
1795 if ( $request->getCheck( 'wpEditToken' ) || $request->getVal( $this->mName ) !== null ) {
1796 // XOR has the following truth table, which is what we want
1797 // INVERT VALUE | OUTPUT
1798 // true true | false
1799 // false true | true
1800 // false false | false
1801 // true false | true
1802 return $request->getBool( $this->mName ) xor $invert;
1803 } else {
1804 return $this->getDefault();
1805 }
1806 }
1807 }
1808
1809 /**
1810 * A checkbox matrix
1811 * Operates similarly to HTMLMultiSelectField, but instead of using an array of
1812 * options, uses an array of rows and an array of columns to dynamically
1813 * construct a matrix of options.
1814 */
1815 class HTMLCheckMatrix extends HTMLFormField {
1816
1817 function validate( $value, $alldata ) {
1818 $rows = $this->mParams['rows'];
1819 $columns = $this->mParams['columns'];
1820
1821 // Make sure user-defined validation callback is run
1822 $p = parent::validate( $value, $alldata );
1823 if ( $p !== true ) {
1824 return $p;
1825 }
1826
1827 // Make sure submitted value is an array
1828 if ( !is_array( $value ) ) {
1829 return false;
1830 }
1831
1832 // If all options are valid, array_intersect of the valid options
1833 // and the provided options will return the provided options.
1834 $validOptions = array();
1835 foreach ( $rows as $rowTag ) {
1836 foreach ( $columns as $columnTag ) {
1837 $validOptions[] = $columnTag . '-' . $rowTag;
1838 }
1839 }
1840 $validValues = array_intersect( $value, $validOptions );
1841 if ( count( $validValues ) == count( $value ) ) {
1842 return true;
1843 } else {
1844 return $this->msg( 'htmlform-select-badoption' )->parse();
1845 }
1846 }
1847
1848 /**
1849 * Build a table containing a matrix of checkbox options.
1850 * The value of each option is a combination of the row tag and column tag.
1851 * mParams['rows'] is an array with row labels as keys and row tags as values.
1852 * mParams['columns'] is an array with column labels as keys and column tags as values.
1853 * @param array $value of the options that should be checked
1854 * @return String
1855 */
1856 function getInputHTML( $value ) {
1857 $html = '';
1858 $tableContents = '';
1859 $attribs = array();
1860 $rows = $this->mParams['rows'];
1861 $columns = $this->mParams['columns'];
1862
1863 // If the disabled param is set, disable all the options
1864 if ( !empty( $this->mParams['disabled'] ) ) {
1865 $attribs['disabled'] = 'disabled';
1866 }
1867
1868 // Build the column headers
1869 $headerContents = Html::rawElement( 'td', array(), '&#160;' );
1870 foreach ( $columns as $columnLabel => $columnTag ) {
1871 $headerContents .= Html::rawElement( 'td', array(), $columnLabel );
1872 }
1873 $tableContents .= Html::rawElement( 'tr', array(), "\n$headerContents\n" );
1874
1875 // Build the options matrix
1876 foreach ( $rows as $rowLabel => $rowTag ) {
1877 $rowContents = Html::rawElement( 'td', array(), $rowLabel );
1878 foreach ( $columns as $columnTag ) {
1879 // Knock out any options that are not wanted
1880 if ( isset( $this->mParams['remove-options'] )
1881 && in_array( "$columnTag-$rowTag", $this->mParams['remove-options'] ) )
1882 {
1883 $rowContents .= Html::rawElement( 'td', array(), '&#160;' );
1884 } else {
1885 // Construct the checkbox
1886 $thisAttribs = array(
1887 'id' => "{$this->mID}-$columnTag-$rowTag",
1888 'value' => $columnTag . '-' . $rowTag
1889 );
1890 $checkbox = Xml::check(
1891 $this->mName . '[]',
1892 in_array( $columnTag . '-' . $rowTag, (array)$value, true ),
1893 $attribs + $thisAttribs );
1894 $rowContents .= Html::rawElement( 'td', array(), $checkbox );
1895 }
1896 }
1897 $tableContents .= Html::rawElement( 'tr', array(), "\n$rowContents\n" );
1898 }
1899
1900 // Put it all in a table
1901 $html .= Html::rawElement( 'table', array( 'class' => 'mw-htmlform-matrix' ),
1902 Html::rawElement( 'tbody', array(), "\n$tableContents\n" ) ) . "\n";
1903
1904 return $html;
1905 }
1906
1907 /**
1908 * Get the complete table row for the input, including help text,
1909 * labels, and whatever.
1910 * We override this function since the label should always be on a separate
1911 * line above the options in the case of a checkbox matrix, i.e. it's always
1912 * a "vertical-label".
1913 * @param string $value the value to set the input to
1914 * @return String complete HTML table row
1915 */
1916 function getTableRow( $value ) {
1917 list( $errors, $errorClass ) = $this->getErrorsAndErrorClass( $value );
1918 $inputHtml = $this->getInputHTML( $value );
1919 $fieldType = get_class( $this );
1920 $helptext = $this->getHelpTextHtmlTable( $this->getHelpText() );
1921 $cellAttributes = array( 'colspan' => 2 );
1922
1923 $label = $this->getLabelHtml( $cellAttributes );
1924
1925 $field = Html::rawElement(
1926 'td',
1927 array( 'class' => 'mw-input' ) + $cellAttributes,
1928 $inputHtml . "\n$errors"
1929 );
1930
1931 $html = Html::rawElement( 'tr',
1932 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
1933 $html .= Html::rawElement( 'tr',
1934 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass} $errorClass" ),
1935 $field );
1936
1937 return $html . $helptext;
1938 }
1939
1940 /**
1941 * @param $request WebRequest
1942 * @return Array
1943 */
1944 function loadDataFromRequest( $request ) {
1945 if ( $this->mParent->getMethod() == 'post' ) {
1946 if ( $request->wasPosted() ) {
1947 // Checkboxes are not added to the request arrays if they're not checked,
1948 // so it's perfectly possible for there not to be an entry at all
1949 return $request->getArray( $this->mName, array() );
1950 } else {
1951 // That's ok, the user has not yet submitted the form, so show the defaults
1952 return $this->getDefault();
1953 }
1954 } else {
1955 // This is the impossible case: if we look at $_GET and see no data for our
1956 // field, is it because the user has not yet submitted the form, or that they
1957 // have submitted it with all the options unchecked. We will have to assume the
1958 // latter, which basically means that you can't specify 'positive' defaults
1959 // for GET forms.
1960 return $request->getArray( $this->mName, array() );
1961 }
1962 }
1963
1964 function getDefault() {
1965 if ( isset( $this->mDefault ) ) {
1966 return $this->mDefault;
1967 } else {
1968 return array();
1969 }
1970 }
1971 }
1972
1973 /**
1974 * A select dropdown field. Basically a wrapper for Xmlselect class
1975 */
1976 class HTMLSelectField extends HTMLFormField {
1977 function validate( $value, $alldata ) {
1978 $p = parent::validate( $value, $alldata );
1979
1980 if ( $p !== true ) {
1981 return $p;
1982 }
1983
1984 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1985
1986 if ( in_array( $value, $validOptions ) ) {
1987 return true;
1988 } else {
1989 return $this->msg( 'htmlform-select-badoption' )->parse();
1990 }
1991 }
1992
1993 function getInputHTML( $value ) {
1994 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1995
1996 # If one of the options' 'name' is int(0), it is automatically selected.
1997 # because PHP sucks and thinks int(0) == 'some string'.
1998 # Working around this by forcing all of them to strings.
1999 foreach ( $this->mParams['options'] as &$opt ) {
2000 if ( is_int( $opt ) ) {
2001 $opt = strval( $opt );
2002 }
2003 }
2004 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
2005
2006 if ( !empty( $this->mParams['disabled'] ) ) {
2007 $select->setAttribute( 'disabled', 'disabled' );
2008 }
2009
2010 if ( $this->mClass !== '' ) {
2011 $select->setAttribute( 'class', $this->mClass );
2012 }
2013
2014 $select->addOptions( $this->mParams['options'] );
2015
2016 return $select->getHTML();
2017 }
2018 }
2019
2020 /**
2021 * Select dropdown field, with an additional "other" textbox.
2022 */
2023 class HTMLSelectOrOtherField extends HTMLTextField {
2024
2025 function __construct( $params ) {
2026 if ( !in_array( 'other', $params['options'], true ) ) {
2027 $msg = isset( $params['other'] ) ?
2028 $params['other'] :
2029 wfMessage( 'htmlform-selectorother-other' )->text();
2030 $params['options'][$msg] = 'other';
2031 }
2032
2033 parent::__construct( $params );
2034 }
2035
2036 static function forceToStringRecursive( $array ) {
2037 if ( is_array( $array ) ) {
2038 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
2039 } else {
2040 return strval( $array );
2041 }
2042 }
2043
2044 function getInputHTML( $value ) {
2045 $valInSelect = false;
2046
2047 if ( $value !== false ) {
2048 $valInSelect = in_array(
2049 $value,
2050 HTMLFormField::flattenOptions( $this->mParams['options'] )
2051 );
2052 }
2053
2054 $selected = $valInSelect ? $value : 'other';
2055
2056 $opts = self::forceToStringRecursive( $this->mParams['options'] );
2057
2058 $select = new XmlSelect( $this->mName, $this->mID, $selected );
2059 $select->addOptions( $opts );
2060
2061 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
2062
2063 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
2064
2065 if ( !empty( $this->mParams['disabled'] ) ) {
2066 $select->setAttribute( 'disabled', 'disabled' );
2067 $tbAttribs['disabled'] = 'disabled';
2068 }
2069
2070 $select = $select->getHTML();
2071
2072 if ( isset( $this->mParams['maxlength'] ) ) {
2073 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
2074 }
2075
2076 if ( $this->mClass !== '' ) {
2077 $tbAttribs['class'] = $this->mClass;
2078 }
2079
2080 $textbox = Html::input(
2081 $this->mName . '-other',
2082 $valInSelect ? '' : $value,
2083 'text',
2084 $tbAttribs
2085 );
2086
2087 return "$select<br />\n$textbox";
2088 }
2089
2090 /**
2091 * @param $request WebRequest
2092 * @return String
2093 */
2094 function loadDataFromRequest( $request ) {
2095 if ( $request->getCheck( $this->mName ) ) {
2096 $val = $request->getText( $this->mName );
2097
2098 if ( $val == 'other' ) {
2099 $val = $request->getText( $this->mName . '-other' );
2100 }
2101
2102 return $val;
2103 } else {
2104 return $this->getDefault();
2105 }
2106 }
2107 }
2108
2109 /**
2110 * Multi-select field
2111 */
2112 class HTMLMultiSelectField extends HTMLFormField {
2113
2114 function validate( $value, $alldata ) {
2115 $p = parent::validate( $value, $alldata );
2116
2117 if ( $p !== true ) {
2118 return $p;
2119 }
2120
2121 if ( !is_array( $value ) ) {
2122 return false;
2123 }
2124
2125 # If all options are valid, array_intersect of the valid options
2126 # and the provided options will return the provided options.
2127 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2128
2129 $validValues = array_intersect( $value, $validOptions );
2130 if ( count( $validValues ) == count( $value ) ) {
2131 return true;
2132 } else {
2133 return $this->msg( 'htmlform-select-badoption' )->parse();
2134 }
2135 }
2136
2137 function getInputHTML( $value ) {
2138 $html = $this->formatOptions( $this->mParams['options'], $value );
2139
2140 return $html;
2141 }
2142
2143 function formatOptions( $options, $value ) {
2144 $html = '';
2145
2146 $attribs = array();
2147
2148 if ( !empty( $this->mParams['disabled'] ) ) {
2149 $attribs['disabled'] = 'disabled';
2150 }
2151
2152 foreach ( $options as $label => $info ) {
2153 if ( is_array( $info ) ) {
2154 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2155 $html .= $this->formatOptions( $info, $value );
2156 } else {
2157 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
2158
2159 $checkbox = Xml::check(
2160 $this->mName . '[]',
2161 in_array( $info, $value, true ),
2162 $attribs + $thisAttribs );
2163 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
2164
2165 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $checkbox );
2166 }
2167 }
2168
2169 return $html;
2170 }
2171
2172 /**
2173 * @param $request WebRequest
2174 * @return String
2175 */
2176 function loadDataFromRequest( $request ) {
2177 if ( $this->mParent->getMethod() == 'post' ) {
2178 if ( $request->wasPosted() ) {
2179 # Checkboxes are just not added to the request arrays if they're not checked,
2180 # so it's perfectly possible for there not to be an entry at all
2181 return $request->getArray( $this->mName, array() );
2182 } else {
2183 # That's ok, the user has not yet submitted the form, so show the defaults
2184 return $this->getDefault();
2185 }
2186 } else {
2187 # This is the impossible case: if we look at $_GET and see no data for our
2188 # field, is it because the user has not yet submitted the form, or that they
2189 # have submitted it with all the options unchecked? We will have to assume the
2190 # latter, which basically means that you can't specify 'positive' defaults
2191 # for GET forms.
2192 # @todo FIXME...
2193 return $request->getArray( $this->mName, array() );
2194 }
2195 }
2196
2197 function getDefault() {
2198 if ( isset( $this->mDefault ) ) {
2199 return $this->mDefault;
2200 } else {
2201 return array();
2202 }
2203 }
2204
2205 protected function needsLabel() {
2206 return false;
2207 }
2208 }
2209
2210 /**
2211 * Double field with a dropdown list constructed from a system message in the format
2212 * * Optgroup header
2213 * ** <option value>
2214 * * New Optgroup header
2215 * Plus a text field underneath for an additional reason. The 'value' of the field is
2216 * "<select>: <extra reason>", or "<extra reason>" if nothing has been selected in the
2217 * select dropdown.
2218 * @todo FIXME: If made 'required', only the text field should be compulsory.
2219 */
2220 class HTMLSelectAndOtherField extends HTMLSelectField {
2221
2222 function __construct( $params ) {
2223 if ( array_key_exists( 'other', $params ) ) {
2224 } elseif ( array_key_exists( 'other-message', $params ) ) {
2225 $params['other'] = wfMessage( $params['other-message'] )->plain();
2226 } else {
2227 $params['other'] = null;
2228 }
2229
2230 if ( array_key_exists( 'options', $params ) ) {
2231 # Options array already specified
2232 } elseif ( array_key_exists( 'options-message', $params ) ) {
2233 # Generate options array from a system message
2234 $params['options'] = self::parseMessage(
2235 wfMessage( $params['options-message'] )->inContentLanguage()->plain(),
2236 $params['other']
2237 );
2238 } else {
2239 # Sulk
2240 throw new MWException( 'HTMLSelectAndOtherField called without any options' );
2241 }
2242 $this->mFlatOptions = self::flattenOptions( $params['options'] );
2243
2244 parent::__construct( $params );
2245 }
2246
2247 /**
2248 * Build a drop-down box from a textual list.
2249 * @param string $string message text
2250 * @param string $otherName name of "other reason" option
2251 * @return Array
2252 * TODO: this is copied from Xml::listDropDown(), deprecate/avoid duplication?
2253 */
2254 public static function parseMessage( $string, $otherName = null ) {
2255 if ( $otherName === null ) {
2256 $otherName = wfMessage( 'htmlform-selectorother-other' )->plain();
2257 }
2258
2259 $optgroup = false;
2260 $options = array( $otherName => 'other' );
2261
2262 foreach ( explode( "\n", $string ) as $option ) {
2263 $value = trim( $option );
2264 if ( $value == '' ) {
2265 continue;
2266 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
2267 # A new group is starting...
2268 $value = trim( substr( $value, 1 ) );
2269 $optgroup = $value;
2270 } elseif ( substr( $value, 0, 2 ) == '**' ) {
2271 # groupmember
2272 $opt = trim( substr( $value, 2 ) );
2273 if ( $optgroup === false ) {
2274 $options[$opt] = $opt;
2275 } else {
2276 $options[$optgroup][$opt] = $opt;
2277 }
2278 } else {
2279 # groupless reason list
2280 $optgroup = false;
2281 $options[$option] = $option;
2282 }
2283 }
2284
2285 return $options;
2286 }
2287
2288 function getInputHTML( $value ) {
2289 $select = parent::getInputHTML( $value[1] );
2290
2291 $textAttribs = array(
2292 'id' => $this->mID . '-other',
2293 'size' => $this->getSize(),
2294 );
2295
2296 if ( $this->mClass !== '' ) {
2297 $textAttribs['class'] = $this->mClass;
2298 }
2299
2300 foreach ( array( 'required', 'autofocus', 'multiple', 'disabled' ) as $param ) {
2301 if ( isset( $this->mParams[$param] ) ) {
2302 $textAttribs[$param] = '';
2303 }
2304 }
2305
2306 $textbox = Html::input(
2307 $this->mName . '-other',
2308 $value[2],
2309 'text',
2310 $textAttribs
2311 );
2312
2313 return "$select<br />\n$textbox";
2314 }
2315
2316 /**
2317 * @param $request WebRequest
2318 * @return Array("<overall message>","<select value>","<text field value>")
2319 */
2320 function loadDataFromRequest( $request ) {
2321 if ( $request->getCheck( $this->mName ) ) {
2322
2323 $list = $request->getText( $this->mName );
2324 $text = $request->getText( $this->mName . '-other' );
2325
2326 if ( $list == 'other' ) {
2327 $final = $text;
2328 } elseif ( !in_array( $list, $this->mFlatOptions ) ) {
2329 # User has spoofed the select form to give an option which wasn't
2330 # in the original offer. Sulk...
2331 $final = $text;
2332 } elseif ( $text == '' ) {
2333 $final = $list;
2334 } else {
2335 $final = $list . $this->msg( 'colon-separator' )->inContentLanguage()->text() . $text;
2336 }
2337
2338 } else {
2339 $final = $this->getDefault();
2340
2341 $list = 'other';
2342 $text = $final;
2343 foreach ( $this->mFlatOptions as $option ) {
2344 $match = $option . $this->msg( 'colon-separator' )->inContentLanguage()->text();
2345 if ( strpos( $text, $match ) === 0 ) {
2346 $list = $option;
2347 $text = substr( $text, strlen( $match ) );
2348 break;
2349 }
2350 }
2351 }
2352 return array( $final, $list, $text );
2353 }
2354
2355 function getSize() {
2356 return isset( $this->mParams['size'] )
2357 ? $this->mParams['size']
2358 : 45;
2359 }
2360
2361 function validate( $value, $alldata ) {
2362 # HTMLSelectField forces $value to be one of the options in the select
2363 # field, which is not useful here. But we do want the validation further up
2364 # the chain
2365 $p = parent::validate( $value[1], $alldata );
2366
2367 if ( $p !== true ) {
2368 return $p;
2369 }
2370
2371 if ( isset( $this->mParams['required'] ) && $this->mParams['required'] !== false && $value[1] === '' ) {
2372 return $this->msg( 'htmlform-required' )->parse();
2373 }
2374
2375 return true;
2376 }
2377 }
2378
2379 /**
2380 * Radio checkbox fields.
2381 */
2382 class HTMLRadioField extends HTMLFormField {
2383
2384 function validate( $value, $alldata ) {
2385 $p = parent::validate( $value, $alldata );
2386
2387 if ( $p !== true ) {
2388 return $p;
2389 }
2390
2391 if ( !is_string( $value ) && !is_int( $value ) ) {
2392 return false;
2393 }
2394
2395 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
2396
2397 if ( in_array( $value, $validOptions ) ) {
2398 return true;
2399 } else {
2400 return $this->msg( 'htmlform-select-badoption' )->parse();
2401 }
2402 }
2403
2404 /**
2405 * This returns a block of all the radio options, in one cell.
2406 * @see includes/HTMLFormField#getInputHTML()
2407 * @param $value String
2408 * @return String
2409 */
2410 function getInputHTML( $value ) {
2411 $html = $this->formatOptions( $this->mParams['options'], $value );
2412
2413 return $html;
2414 }
2415
2416 function formatOptions( $options, $value ) {
2417 $html = '';
2418
2419 $attribs = array();
2420 if ( !empty( $this->mParams['disabled'] ) ) {
2421 $attribs['disabled'] = 'disabled';
2422 }
2423
2424 # TODO: should this produce an unordered list perhaps?
2425 foreach ( $options as $label => $info ) {
2426 if ( is_array( $info ) ) {
2427 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
2428 $html .= $this->formatOptions( $info, $value );
2429 } else {
2430 $id = Sanitizer::escapeId( $this->mID . "-$info" );
2431 $radio = Xml::radio(
2432 $this->mName,
2433 $info,
2434 $info == $value,
2435 $attribs + array( 'id' => $id )
2436 );
2437 $radio .= '&#160;' .
2438 Html::rawElement( 'label', array( 'for' => $id ), $label );
2439
2440 $html .= ' ' . Html::rawElement( 'div', array( 'class' => 'mw-htmlform-flatlist-item' ), $radio );
2441 }
2442 }
2443
2444 return $html;
2445 }
2446
2447 protected function needsLabel() {
2448 return false;
2449 }
2450 }
2451
2452 /**
2453 * An information field (text blob), not a proper input.
2454 */
2455 class HTMLInfoField extends HTMLFormField {
2456 public function __construct( $info ) {
2457 $info['nodata'] = true;
2458
2459 parent::__construct( $info );
2460 }
2461
2462 public function getInputHTML( $value ) {
2463 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
2464 }
2465
2466 public function getTableRow( $value ) {
2467 if ( !empty( $this->mParams['rawrow'] ) ) {
2468 return $value;
2469 }
2470
2471 return parent::getTableRow( $value );
2472 }
2473
2474 /**
2475 * @since 1.20
2476 */
2477 public function getDiv( $value ) {
2478 if ( !empty( $this->mParams['rawrow'] ) ) {
2479 return $value;
2480 }
2481
2482 return parent::getDiv( $value );
2483 }
2484
2485 /**
2486 * @since 1.20
2487 */
2488 public function getRaw( $value ) {
2489 if ( !empty( $this->mParams['rawrow'] ) ) {
2490 return $value;
2491 }
2492
2493 return parent::getRaw( $value );
2494 }
2495
2496 protected function needsLabel() {
2497 return false;
2498 }
2499 }
2500
2501 class HTMLHiddenField extends HTMLFormField {
2502 public function __construct( $params ) {
2503 parent::__construct( $params );
2504
2505 # Per HTML5 spec, hidden fields cannot be 'required'
2506 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
2507 unset( $this->mParams['required'] );
2508 }
2509
2510 public function getTableRow( $value ) {
2511 $params = array();
2512 if ( $this->mID ) {
2513 $params['id'] = $this->mID;
2514 }
2515
2516 $this->mParent->addHiddenField(
2517 $this->mName,
2518 $this->mDefault,
2519 $params
2520 );
2521
2522 return '';
2523 }
2524
2525 /**
2526 * @since 1.20
2527 */
2528 public function getDiv( $value ) {
2529 return $this->getTableRow( $value );
2530 }
2531
2532 /**
2533 * @since 1.20
2534 */
2535 public function getRaw( $value ) {
2536 return $this->getTableRow( $value );
2537 }
2538
2539 public function getInputHTML( $value ) {
2540 return '';
2541 }
2542 }
2543
2544 /**
2545 * Add a submit button inline in the form (as opposed to
2546 * HTMLForm::addButton(), which will add it at the end).
2547 */
2548 class HTMLSubmitField extends HTMLButtonField {
2549 protected $buttonType = 'submit';
2550 }
2551
2552 /**
2553 * Adds a generic button inline to the form. Does not do anything, you must add
2554 * click handling code in JavaScript. Use a HTMLSubmitField if you merely
2555 * wish to add a submit button to a form.
2556 *
2557 * @since 1.22
2558 */
2559 class HTMLButtonField extends HTMLFormField {
2560 protected $buttonType = 'button';
2561
2562 public function __construct( $info ) {
2563 $info['nodata'] = true;
2564 parent::__construct( $info );
2565 }
2566
2567 public function getInputHTML( $value ) {
2568 $attr = array(
2569 'class' => 'mw-htmlform-submit ' . $this->mClass,
2570 'id' => $this->mID,
2571 );
2572
2573 if ( !empty( $this->mParams['disabled'] ) ) {
2574 $attr['disabled'] = 'disabled';
2575 }
2576
2577 return Html::input(
2578 $this->mName,
2579 $value,
2580 $this->buttonType,
2581 $attr
2582 );
2583 }
2584
2585 protected function needsLabel() {
2586 return false;
2587 }
2588
2589 /**
2590 * Button cannot be invalid
2591 * @param $value String
2592 * @param $alldata Array
2593 * @return Bool
2594 */
2595 public function validate( $value, $alldata ) {
2596 return true;
2597 }
2598 }
2599
2600 class HTMLEditTools extends HTMLFormField {
2601 public function getInputHTML( $value ) {
2602 return '';
2603 }
2604
2605 public function getTableRow( $value ) {
2606 $msg = $this->formatMsg();
2607
2608 return '<tr><td></td><td class="mw-input">'
2609 . '<div class="mw-editTools">'
2610 . $msg->parseAsBlock()
2611 . "</div></td></tr>\n";
2612 }
2613
2614 /**
2615 * @since 1.20
2616 */
2617 public function getDiv( $value ) {
2618 $msg = $this->formatMsg();
2619 return '<div class="mw-editTools">' . $msg->parseAsBlock() . '</div>';
2620 }
2621
2622 /**
2623 * @since 1.20
2624 */
2625 public function getRaw( $value ) {
2626 return $this->getDiv( $value );
2627 }
2628
2629 protected function formatMsg() {
2630 if ( empty( $this->mParams['message'] ) ) {
2631 $msg = $this->msg( 'edittools' );
2632 } else {
2633 $msg = $this->msg( $this->mParams['message'] );
2634 if ( $msg->isDisabled() ) {
2635 $msg = $this->msg( 'edittools' );
2636 }
2637 }
2638 $msg->inContentLanguage();
2639 return $msg;
2640 }
2641 }
2642
2643 class HTMLApiField extends HTMLFormField {
2644 public function getTableRow( $value ) {
2645 return '';
2646 }
2647
2648 public function getDiv( $value ) {
2649 return $this->getTableRow( $value );
2650 }
2651
2652 public function getRaw( $value ) {
2653 return $this->getTableRow( $value );
2654 }
2655
2656 public function getInputHTML( $value ) {
2657 return '';
2658 }
2659 }