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