Don't look for pipes in the root node.
[lhc/web/wiklou.git] / includes / HTMLForm.php
1 <?php
2 /**
3 * Object handling generic submission, CSRF protection, layout and
4 * other logic for UI forms. in a reusable manner.
5 *
6 * In order to generate the form, the HTMLForm object takes an array
7 * structure detailing the form fields available. Each element of the
8 * array is a basic property-list, including the type of field, the
9 * label it is to be given in the form, callbacks for validation and
10 * 'filtering', and other pertinent information.
11 *
12 * Field types are implemented as subclasses of the generic HTMLFormField
13 * object, and typically implement at least getInputHTML, which generates
14 * the HTML for the input field to be placed in the table.
15 *
16 * The constructor input is an associative array of $fieldname => $info,
17 * where $info is an Associative Array with any of the following:
18 *
19 * 'class' -- the subclass of HTMLFormField that will be used
20 * to create the object. *NOT* the CSS class!
21 * 'type' -- roughly translates into the <select> type attribute.
22 * if 'class' is not specified, this is used as a map
23 * through HTMLForm::$typeMappings to get the class name.
24 * 'default' -- default value when the form is displayed
25 * 'id' -- HTML id attribute
26 * 'cssclass' -- CSS class
27 * 'options' -- varies according to the specific object.
28 * 'label-message' -- message key for a message to use as the label.
29 * can be an array of msg key and then parameters to
30 * the message.
31 * 'label' -- alternatively, a raw text message. Overridden by
32 * label-message
33 * 'help-message' -- message key for a message to use as a help text.
34 * can be an array of msg key and then parameters to
35 * the message.
36 * Overwrites 'help-messages'.
37 * 'help-messages' -- array of message key. As above, each item can
38 * be an array of msg key and then parameters.
39 * Overwrites 'help-message'.
40 * 'required' -- passed through to the object, indicating that it
41 * is a required field.
42 * 'size' -- the length of text fields
43 * 'filter-callback -- a function name to give you the chance to
44 * massage the inputted value before it's processed.
45 * @see HTMLForm::filter()
46 * 'validation-callback' -- a function name to give you the chance
47 * to impose extra validation on the field input.
48 * @see HTMLForm::validate()
49 * 'name' -- By default, the 'name' attribute of the input field
50 * is "wp{$fieldname}". If you want a different name
51 * (eg one without the "wp" prefix), specify it here and
52 * it will be used without modification.
53 *
54 * TODO: Document 'section' / 'subsection' stuff
55 */
56 class HTMLForm {
57 static $jsAdded = false;
58
59 # A mapping of 'type' inputs onto standard HTMLFormField subclasses
60 static $typeMappings = array(
61 'text' => 'HTMLTextField',
62 'textarea' => 'HTMLTextAreaField',
63 'select' => 'HTMLSelectField',
64 'radio' => 'HTMLRadioField',
65 'multiselect' => 'HTMLMultiSelectField',
66 'check' => 'HTMLCheckField',
67 'toggle' => 'HTMLCheckField',
68 'int' => 'HTMLIntField',
69 'float' => 'HTMLFloatField',
70 'info' => 'HTMLInfoField',
71 'selectorother' => 'HTMLSelectOrOtherField',
72 'submit' => 'HTMLSubmitField',
73 'hidden' => 'HTMLHiddenField',
74 'edittools' => 'HTMLEditTools',
75
76 # HTMLTextField will output the correct type="" attribute automagically.
77 # There are about four zillion other HTML5 input types, like url, but
78 # we don't use those at the moment, so no point in adding all of them.
79 'email' => 'HTMLTextField',
80 'password' => 'HTMLTextField',
81 );
82
83 protected $mMessagePrefix;
84 protected $mFlatFields;
85 protected $mFieldTree;
86 protected $mShowReset = false;
87 public $mFieldData;
88
89 protected $mSubmitCallback;
90 protected $mValidationErrorMessage;
91
92 protected $mPre = '';
93 protected $mHeader = '';
94 protected $mFooter = '';
95 protected $mPost = '';
96 protected $mId;
97
98 protected $mSubmitID;
99 protected $mSubmitName;
100 protected $mSubmitText;
101 protected $mSubmitTooltip;
102 protected $mTitle;
103 protected $mMethod = 'post';
104
105 protected $mUseMultipart = false;
106 protected $mHiddenFields = array();
107 protected $mButtons = array();
108
109 protected $mWrapperLegend = false;
110
111 /**
112 * Build a new HTMLForm from an array of field attributes
113 * @param $descriptor Array of Field constructs, as described above
114 * @param $messagePrefix String a prefix to go in front of default messages
115 */
116 public function __construct( $descriptor, $messagePrefix = '' ) {
117 $this->mMessagePrefix = $messagePrefix;
118
119 // Expand out into a tree.
120 $loadedDescriptor = array();
121 $this->mFlatFields = array();
122
123 foreach ( $descriptor as $fieldname => $info ) {
124 $section = isset( $info['section'] )
125 ? $info['section']
126 : '';
127
128 if ( isset( $info['type'] ) && $info['type'] == 'file' ) {
129 $this->mUseMultipart = true;
130 }
131
132 $field = self::loadInputFromParameters( $fieldname, $info );
133 $field->mParent = $this;
134
135 $setSection =& $loadedDescriptor;
136 if ( $section ) {
137 $sectionParts = explode( '/', $section );
138
139 while ( count( $sectionParts ) ) {
140 $newName = array_shift( $sectionParts );
141
142 if ( !isset( $setSection[$newName] ) ) {
143 $setSection[$newName] = array();
144 }
145
146 $setSection =& $setSection[$newName];
147 }
148 }
149
150 $setSection[$fieldname] = $field;
151 $this->mFlatFields[$fieldname] = $field;
152 }
153
154 $this->mFieldTree = $loadedDescriptor;
155 }
156
157 /**
158 * Add the HTMLForm-specific JavaScript, if it hasn't been
159 * done already.
160 */
161 static function addJS() {
162 if ( self::$jsAdded ) return;
163
164 global $wgOut;
165
166 $wgOut->addModules( 'mediawiki.legacy.htmlform' );
167 }
168
169 /**
170 * Initialise a new Object for the field
171 * @param $descriptor input Descriptor, as described above
172 * @return HTMLFormField subclass
173 */
174 static function loadInputFromParameters( $fieldname, $descriptor ) {
175 if ( isset( $descriptor['class'] ) ) {
176 $class = $descriptor['class'];
177 } elseif ( isset( $descriptor['type'] ) ) {
178 $class = self::$typeMappings[$descriptor['type']];
179 $descriptor['class'] = $class;
180 }
181
182 if ( !$class ) {
183 throw new MWException( "Descriptor with no class: " . print_r( $descriptor, true ) );
184 }
185
186 $descriptor['fieldname'] = $fieldname;
187
188 $obj = new $class( $descriptor );
189
190 return $obj;
191 }
192
193 /**
194 * Prepare form for submission
195 */
196 function prepareForm() {
197 # Check if we have the info we need
198 if ( ! $this->mTitle ) {
199 throw new MWException( "You must call setTitle() on an HTMLForm" );
200 }
201
202 // FIXME shouldn't this be closer to displayForm() ?
203 self::addJS();
204
205 # Load data from the request.
206 $this->loadData();
207 }
208
209 /**
210 * Try submitting, with edit token check first
211 * @return Status|boolean
212 */
213 function tryAuthorizedSubmit() {
214 global $wgUser, $wgRequest;
215 $editToken = $wgRequest->getVal( 'wpEditToken' );
216
217 $result = false;
218 if ( $this->getMethod() != 'post' || $wgUser->matchEditToken( $editToken ) ) {
219 $result = $this->trySubmit();
220 }
221 return $result;
222 }
223
224 /**
225 * The here's-one-I-made-earlier option: do the submission if
226 * posted, or display the form with or without funky valiation
227 * errors
228 * @return Bool or Status whether submission was successful.
229 */
230 function show() {
231 $this->prepareForm();
232
233 $result = $this->tryAuthorizedSubmit();
234 if ( $result === true || ( $result instanceof Status && $result->isGood() ) ){
235 return $result;
236 }
237
238 $this->displayForm( $result );
239 return false;
240 }
241
242 /**
243 * Validate all the fields, and call the submision callback
244 * function if everything is kosher.
245 * @return Mixed Bool true == Successful submission, Bool false
246 * == No submission attempted, anything else == Error to
247 * display.
248 */
249 function trySubmit() {
250 # Check for validation
251 foreach ( $this->mFlatFields as $fieldname => $field ) {
252 if ( !empty( $field->mParams['nodata'] ) ) {
253 continue;
254 }
255 if ( $field->validate(
256 $this->mFieldData[$fieldname],
257 $this->mFieldData )
258 !== true
259 ) {
260 return isset( $this->mValidationErrorMessage )
261 ? $this->mValidationErrorMessage
262 : array( 'htmlform-invalid-input' );
263 }
264 }
265
266 $callback = $this->mSubmitCallback;
267
268 $data = $this->filterDataForSubmit( $this->mFieldData );
269
270 $res = call_user_func( $callback, $data );
271
272 return $res;
273 }
274
275 /**
276 * Set a callback to a function to do something with the form
277 * once it's been successfully validated.
278 * @param $cb String function name. The function will be passed
279 * the output from HTMLForm::filterDataForSubmit, and must
280 * return Bool true on success, Bool false if no submission
281 * was attempted, or String HTML output to display on error.
282 */
283 function setSubmitCallback( $cb ) {
284 $this->mSubmitCallback = $cb;
285 }
286
287 /**
288 * Set a message to display on a validation error.
289 * @param $msg Mixed String or Array of valid inputs to wfMsgExt()
290 * (so each entry can be either a String or Array)
291 */
292 function setValidationErrorMessage( $msg ) {
293 $this->mValidationErrorMessage = $msg;
294 }
295
296 /**
297 * Set the introductory message, overwriting any existing message.
298 * @param $msg String complete text of message to display
299 */
300 function setIntro( $msg ) { $this->mPre = $msg; }
301
302 /**
303 * Add introductory text.
304 * @param $msg String complete text of message to display
305 */
306 function addPreText( $msg ) { $this->mPre .= $msg; }
307
308 /**
309 * Add header text, inside the form.
310 * @param $msg String complete text of message to display
311 */
312 function addHeaderText( $msg ) { $this->mHeader .= $msg; }
313
314 /**
315 * Add footer text, inside the form.
316 * @param $msg String complete text of message to display
317 */
318 function addFooterText( $msg ) { $this->mFooter .= $msg; }
319
320 /**
321 * Add text to the end of the display.
322 * @param $msg String complete text of message to display
323 */
324 function addPostText( $msg ) { $this->mPost .= $msg; }
325
326 /**
327 * Add a hidden field to the output
328 * @param $name String field name. This will be used exactly as entered
329 * @param $value String field value
330 * @param $attribs Array
331 */
332 public function addHiddenField( $name, $value, $attribs = array() ) {
333 $attribs += array( 'name' => $name );
334 $this->mHiddenFields[] = array( $value, $attribs );
335 }
336
337 public function addButton( $name, $value, $id = null, $attribs = null ) {
338 $this->mButtons[] = compact( 'name', 'value', 'id', 'attribs' );
339 }
340
341 /**
342 * Display the form (sending to wgOut), with an appropriate error
343 * message or stack of messages, and any validation errors, etc.
344 * @param $submitResult Mixed output from HTMLForm::trySubmit()
345 */
346 function displayForm( $submitResult ) {
347 global $wgOut;
348
349 # For good measure (it is the default)
350 $wgOut->preventClickjacking();
351
352 $html = ''
353 . $this->getErrors( $submitResult )
354 . $this->mHeader
355 . $this->getBody()
356 . $this->getHiddenFields()
357 . $this->getButtons()
358 . $this->mFooter
359 ;
360
361 $html = $this->wrapForm( $html );
362
363 $wgOut->addHTML( ''
364 . $this->mPre
365 . $html
366 . $this->mPost
367 );
368 }
369
370 /**
371 * Wrap the form innards in an actual <form> element
372 * @param $html String HTML contents to wrap.
373 * @return String wrapped HTML.
374 */
375 function wrapForm( $html ) {
376
377 # Include a <fieldset> wrapper for style, if requested.
378 if ( $this->mWrapperLegend !== false ) {
379 $html = Xml::fieldset( $this->mWrapperLegend, $html );
380 }
381 # Use multipart/form-data
382 $encType = $this->mUseMultipart
383 ? 'multipart/form-data'
384 : 'application/x-www-form-urlencoded';
385 # Attributes
386 $attribs = array(
387 'action' => $this->getTitle()->getFullURL(),
388 'method' => $this->mMethod,
389 'class' => 'visualClear',
390 'enctype' => $encType,
391 );
392 if ( !empty( $this->mId ) ) {
393 $attribs['id'] = $this->mId;
394 }
395
396 return Html::rawElement( 'form', $attribs, $html );
397 }
398
399 /**
400 * Get the hidden fields that should go inside the form.
401 * @return String HTML.
402 */
403 function getHiddenFields() {
404 global $wgUser;
405
406 $html = '';
407
408 if( $this->getMethod() == 'post' ){
409 $html .= Html::hidden( 'wpEditToken', $wgUser->editToken(), array( 'id' => 'wpEditToken' ) ) . "\n";
410 $html .= Html::hidden( 'title', $this->getTitle()->getPrefixedText() ) . "\n";
411 }
412
413 foreach ( $this->mHiddenFields as $data ) {
414 list( $value, $attribs ) = $data;
415 $html .= Html::hidden( $attribs['name'], $value, $attribs ) . "\n";
416 }
417
418 return $html;
419 }
420
421 /**
422 * Get the submit and (potentially) reset buttons.
423 * @return String HTML.
424 */
425 function getButtons() {
426 $html = '';
427 $attribs = array();
428
429 if ( isset( $this->mSubmitID ) ) {
430 $attribs['id'] = $this->mSubmitID;
431 }
432
433 if ( isset( $this->mSubmitName ) ) {
434 $attribs['name'] = $this->mSubmitName;
435 }
436
437 if ( isset( $this->mSubmitTooltip ) ) {
438 global $wgUser;
439 $attribs += $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mSubmitTooltip );
440 }
441
442 $attribs['class'] = 'mw-htmlform-submit';
443
444 $html .= Xml::submitButton( $this->getSubmitText(), $attribs ) . "\n";
445
446 if ( $this->mShowReset ) {
447 $html .= Html::element(
448 'input',
449 array(
450 'type' => 'reset',
451 'value' => wfMsg( 'htmlform-reset' )
452 )
453 ) . "\n";
454 }
455
456 foreach ( $this->mButtons as $button ) {
457 $attrs = array(
458 'type' => 'submit',
459 'name' => $button['name'],
460 'value' => $button['value']
461 );
462
463 if ( $button['attribs'] ) {
464 $attrs += $button['attribs'];
465 }
466
467 if ( isset( $button['id'] ) ) {
468 $attrs['id'] = $button['id'];
469 }
470
471 $html .= Html::element( 'input', $attrs );
472 }
473
474 return $html;
475 }
476
477 /**
478 * Get the whole body of the form.
479 */
480 function getBody() {
481 return $this->displaySection( $this->mFieldTree );
482 }
483
484 /**
485 * Format and display an error message stack.
486 * @param $errors Mixed String or Array of message keys
487 * @return String
488 */
489 function getErrors( $errors ) {
490 if ( $errors instanceof Status ) {
491 global $wgOut;
492 $errorstr = $wgOut->parse( $errors->getWikiText() );
493 } elseif ( is_array( $errors ) ) {
494 $errorstr = $this->formatErrors( $errors );
495 } else {
496 $errorstr = $errors;
497 }
498
499 return $errorstr
500 ? Html::rawElement( 'div', array( 'class' => 'error' ), $errorstr )
501 : '';
502 }
503
504 /**
505 * Format a stack of error messages into a single HTML string
506 * @param $errors Array of message keys/values
507 * @return String HTML, a <ul> list of errors
508 */
509 static function formatErrors( $errors ) {
510 $errorstr = '';
511
512 foreach ( $errors as $error ) {
513 if ( is_array( $error ) ) {
514 $msg = array_shift( $error );
515 } else {
516 $msg = $error;
517 $error = array();
518 }
519
520 $errorstr .= Html::rawElement(
521 'li',
522 null,
523 wfMsgExt( $msg, array( 'parseinline' ), $error )
524 );
525 }
526
527 $errorstr = Html::rawElement( 'ul', array(), $errorstr );
528
529 return $errorstr;
530 }
531
532 /**
533 * Set the text for the submit button
534 * @param $t String plaintext.
535 */
536 function setSubmitText( $t ) {
537 $this->mSubmitText = $t;
538 }
539
540 /**
541 * Get the text for the submit button, either customised or a default.
542 * @return unknown_type
543 */
544 function getSubmitText() {
545 return $this->mSubmitText
546 ? $this->mSubmitText
547 : wfMsg( 'htmlform-submit' );
548 }
549
550 public function setSubmitName( $name ) {
551 $this->mSubmitName = $name;
552 }
553
554 public function setSubmitTooltip( $name ) {
555 $this->mSubmitTooltip = $name;
556 }
557
558 /**
559 * Set the id for the submit button.
560 * @param $t String. FIXME: Integrity is *not* validated
561 */
562 function setSubmitID( $t ) {
563 $this->mSubmitID = $t;
564 }
565
566 public function setId( $id ) {
567 $this->mId = $id;
568 }
569 /**
570 * Prompt the whole form to be wrapped in a <fieldset>, with
571 * this text as its <legend> element.
572 * @param $legend String HTML to go inside the <legend> element.
573 * Will be escaped
574 */
575 public function setWrapperLegend( $legend ) { $this->mWrapperLegend = $legend; }
576
577 /**
578 * Set the prefix for various default messages
579 * TODO: currently only used for the <fieldset> legend on forms
580 * with multiple sections; should be used elsewhre?
581 * @param $p String
582 */
583 function setMessagePrefix( $p ) {
584 $this->mMessagePrefix = $p;
585 }
586
587 /**
588 * Set the title for form submission
589 * @param $t Title of page the form is on/should be posted to
590 */
591 function setTitle( $t ) {
592 $this->mTitle = $t;
593 }
594
595 /**
596 * Get the title
597 * @return Title
598 */
599 function getTitle() {
600 return $this->mTitle;
601 }
602
603 /**
604 * Set the method used to submit the form
605 * @param $method String
606 */
607 public function setMethod( $method='post' ){
608 $this->mMethod = $method;
609 }
610
611 public function getMethod(){
612 return $this->mMethod;
613 }
614
615 /**
616 * TODO: Document
617 * @param $fields
618 */
619 function displaySection( $fields, $sectionName = '' ) {
620 $tableHtml = '';
621 $subsectionHtml = '';
622 $hasLeftColumn = false;
623
624 foreach ( $fields as $key => $value ) {
625 if ( is_object( $value ) ) {
626 $v = empty( $value->mParams['nodata'] )
627 ? $this->mFieldData[$key]
628 : $value->getDefault();
629 $tableHtml .= $value->getTableRow( $v );
630
631 if ( $value->getLabel() != '&#160;' )
632 $hasLeftColumn = true;
633 } elseif ( is_array( $value ) ) {
634 $section = $this->displaySection( $value, $key );
635 $legend = wfMsg( "{$this->mMessagePrefix}-$key" );
636 $subsectionHtml .= Xml::fieldset( $legend, $section ) . "\n";
637 }
638 }
639
640 $classes = array();
641
642 if ( !$hasLeftColumn ) { // Avoid strange spacing when no labels exist
643 $classes[] = 'mw-htmlform-nolabel';
644 }
645
646 $attribs = array(
647 'class' => implode( ' ', $classes ),
648 );
649
650 if ( $sectionName ) {
651 $attribs['id'] = Sanitizer::escapeId( "mw-htmlform-$sectionName" );
652 }
653
654 $tableHtml = Html::rawElement( 'table', $attribs,
655 Html::rawElement( 'tbody', array(), "\n$tableHtml\n" ) ) . "\n";
656
657 return $subsectionHtml . "\n" . $tableHtml;
658 }
659
660 /**
661 * Construct the form fields from the Descriptor array
662 */
663 function loadData() {
664 global $wgRequest;
665
666 $fieldData = array();
667
668 foreach ( $this->mFlatFields as $fieldname => $field ) {
669 if ( !empty( $field->mParams['nodata'] ) ) {
670 continue;
671 } elseif ( !empty( $field->mParams['disabled'] ) ) {
672 $fieldData[$fieldname] = $field->getDefault();
673 } else {
674 $fieldData[$fieldname] = $field->loadDataFromRequest( $wgRequest );
675 }
676 }
677
678 # Filter data.
679 foreach ( $fieldData as $name => &$value ) {
680 $field = $this->mFlatFields[$name];
681 $value = $field->filter( $value, $this->mFlatFields );
682 }
683
684 $this->mFieldData = $fieldData;
685 }
686
687 /**
688 * Stop a reset button being shown for this form
689 * @param $suppressReset Bool set to false to re-enable the
690 * button again
691 */
692 function suppressReset( $suppressReset = true ) {
693 $this->mShowReset = !$suppressReset;
694 }
695
696 /**
697 * Overload this if you want to apply special filtration routines
698 * to the form as a whole, after it's submitted but before it's
699 * processed.
700 * @param $data
701 * @return unknown_type
702 */
703 function filterDataForSubmit( $data ) {
704 return $data;
705 }
706 }
707
708 /**
709 * The parent class to generate form fields. Any field type should
710 * be a subclass of this.
711 */
712 abstract class HTMLFormField {
713
714 protected $mValidationCallback;
715 protected $mFilterCallback;
716 protected $mName;
717 public $mParams;
718 protected $mLabel; # String label. Set on construction
719 protected $mID;
720 protected $mClass = '';
721 protected $mDefault;
722 public $mParent;
723
724 /**
725 * This function must be implemented to return the HTML to generate
726 * the input object itself. It should not implement the surrounding
727 * table cells/rows, or labels/help messages.
728 * @param $value String the value to set the input to; eg a default
729 * text for a text input.
730 * @return String valid HTML.
731 */
732 abstract function getInputHTML( $value );
733
734 /**
735 * Override this function to add specific validation checks on the
736 * field input. Don't forget to call parent::validate() to ensure
737 * that the user-defined callback mValidationCallback is still run
738 * @param $value String the value the field was submitted with
739 * @param $alldata Array the data collected from the form
740 * @return Mixed Bool true on success, or String error to display.
741 */
742 function validate( $value, $alldata ) {
743 if ( isset( $this->mValidationCallback ) ) {
744 return call_user_func( $this->mValidationCallback, $value, $alldata );
745 }
746
747 if ( isset( $this->mParams['required'] ) && $value === '' ) {
748 return wfMsgExt( 'htmlform-required', 'parseinline' );
749 }
750
751 return true;
752 }
753
754 function filter( $value, $alldata ) {
755 if ( isset( $this->mFilterCallback ) ) {
756 $value = call_user_func( $this->mFilterCallback, $value, $alldata );
757 }
758
759 return $value;
760 }
761
762 /**
763 * Should this field have a label, or is there no input element with the
764 * appropriate id for the label to point to?
765 *
766 * @return bool True to output a label, false to suppress
767 */
768 protected function needsLabel() {
769 return true;
770 }
771
772 /**
773 * Get the value that this input has been set to from a posted form,
774 * or the input's default value if it has not been set.
775 * @param $request WebRequest
776 * @return String the value
777 */
778 function loadDataFromRequest( $request ) {
779 if ( $request->getCheck( $this->mName ) ) {
780 return $request->getText( $this->mName );
781 } else {
782 return $this->getDefault();
783 }
784 }
785
786 /**
787 * Initialise the object
788 * @param $params Associative Array. See HTMLForm doc for syntax.
789 */
790 function __construct( $params ) {
791 $this->mParams = $params;
792
793 # Generate the label from a message, if possible
794 if ( isset( $params['label-message'] ) ) {
795 $msgInfo = $params['label-message'];
796
797 if ( is_array( $msgInfo ) ) {
798 $msg = array_shift( $msgInfo );
799 } else {
800 $msg = $msgInfo;
801 $msgInfo = array();
802 }
803
804 $this->mLabel = wfMsgExt( $msg, 'parseinline', $msgInfo );
805 } elseif ( isset( $params['label'] ) ) {
806 $this->mLabel = $params['label'];
807 }
808
809 $this->mName = "wp{$params['fieldname']}";
810 if ( isset( $params['name'] ) ) {
811 $this->mName = $params['name'];
812 }
813
814 $validName = Sanitizer::escapeId( $this->mName );
815 if ( $this->mName != $validName && !isset( $params['nodata'] ) ) {
816 throw new MWException( "Invalid name '{$this->mName}' passed to " . __METHOD__ );
817 }
818
819 $this->mID = "mw-input-{$this->mName}";
820
821 if ( isset( $params['default'] ) ) {
822 $this->mDefault = $params['default'];
823 }
824
825 if ( isset( $params['id'] ) ) {
826 $id = $params['id'];
827 $validId = Sanitizer::escapeId( $id );
828
829 if ( $id != $validId ) {
830 throw new MWException( "Invalid id '$id' passed to " . __METHOD__ );
831 }
832
833 $this->mID = $id;
834 }
835
836 if ( isset( $params['cssclass'] ) ) {
837 $this->mClass = $params['cssclass'];
838 }
839
840 if ( isset( $params['validation-callback'] ) ) {
841 $this->mValidationCallback = $params['validation-callback'];
842 }
843
844 if ( isset( $params['filter-callback'] ) ) {
845 $this->mFilterCallback = $params['filter-callback'];
846 }
847 }
848
849 /**
850 * Get the complete table row for the input, including help text,
851 * labels, and whatever.
852 * @param $value String the value to set the input to.
853 * @return String complete HTML table row.
854 */
855 function getTableRow( $value ) {
856 # Check for invalid data.
857 global $wgRequest;
858
859 $errors = $this->validate( $value, $this->mParent->mFieldData );
860
861 $cellAttributes = array();
862 $verticalLabel = false;
863
864 if ( !empty($this->mParams['vertical-label']) ) {
865 $cellAttributes['colspan'] = 2;
866 $verticalLabel = true;
867 }
868
869 if ( $errors === true || ( !$wgRequest->wasPosted() && ( $this->mParent->getMethod() == 'post' ) ) ) {
870 $errors = '';
871 } else {
872 $errors = Html::rawElement( 'span', array( 'class' => 'error' ), $errors );
873 }
874
875 $label = $this->getLabelHtml( $cellAttributes );
876 $field = Html::rawElement(
877 'td',
878 array( 'class' => 'mw-input' ) + $cellAttributes,
879 $this->getInputHTML( $value ) . "\n$errors"
880 );
881
882 $fieldType = get_class( $this );
883
884 if ($verticalLabel) {
885 $html = Html::rawElement( 'tr',
886 array( 'class' => 'mw-htmlform-vertical-label' ), $label );
887 $html .= Html::rawElement( 'tr',
888 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
889 $field );
890 } else {
891 $html = Html::rawElement( 'tr',
892 array( 'class' => "mw-htmlform-field-$fieldType {$this->mClass}" ),
893 $label . $field );
894 }
895
896 $helptext = null;
897
898 if ( isset( $this->mParams['help-message'] ) ) {
899 $msg = $this->mParams['help-message'];
900 $helptext = wfMsgExt( $msg, 'parseinline' );
901 if ( wfEmptyMsg( $msg, $helptext ) ) {
902 # Never mind
903 $helptext = null;
904 }
905 } elseif ( isset( $this->mParams['help-messages'] ) ) {
906 # help-message can be passed a message key (string) or an array containing
907 # a message key and additional parameters. This makes it impossible to pass
908 # an array of message key
909 foreach( $this->mParams['help-messages'] as $msg ) {
910 $candidate = wfMsgExt( $msg, 'parseinline' );
911 if( wfEmptyMsg( $msg ) ) {
912 $candidate = null;
913 }
914 $helptext .= $candidate; // append message
915 }
916 } elseif ( isset( $this->mParams['help'] ) ) {
917 $helptext = $this->mParams['help'];
918 }
919
920 if ( !is_null( $helptext ) ) {
921 $row = Html::rawElement( 'td', array( 'colspan' => 2, 'class' => 'htmlform-tip' ),
922 $helptext );
923 $row = Html::rawElement( 'tr', array(), $row );
924 $html .= "$row\n";
925 }
926
927 return $html;
928 }
929
930 function getLabel() {
931 return $this->mLabel;
932 }
933 function getLabelHtml( $cellAttributes = array() ) {
934 # Don't output a for= attribute for labels with no associated input.
935 # Kind of hacky here, possibly we don't want these to be <label>s at all.
936 $for = array();
937
938 if ( $this->needsLabel() ) {
939 $for['for'] = $this->mID;
940 }
941
942 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes,
943 Html::rawElement( 'label', $for, $this->getLabel() )
944 );
945 }
946
947 function getDefault() {
948 if ( isset( $this->mDefault ) ) {
949 return $this->mDefault;
950 } else {
951 return null;
952 }
953 }
954
955 /**
956 * Returns the attributes required for the tooltip and accesskey.
957 *
958 * @return array Attributes
959 */
960 public function getTooltipAndAccessKey() {
961 if ( empty( $this->mParams['tooltip'] ) ) {
962 return array();
963 }
964
965 global $wgUser;
966
967 return $wgUser->getSkin()->tooltipAndAccessKeyAttribs( $this->mParams['tooltip'] );
968 }
969
970 /**
971 * flatten an array of options to a single array, for instance,
972 * a set of <options> inside <optgroups>.
973 * @param $options Associative Array with values either Strings
974 * or Arrays
975 * @return Array flattened input
976 */
977 public static function flattenOptions( $options ) {
978 $flatOpts = array();
979
980 foreach ( $options as $value ) {
981 if ( is_array( $value ) ) {
982 $flatOpts = array_merge( $flatOpts, self::flattenOptions( $value ) );
983 } else {
984 $flatOpts[] = $value;
985 }
986 }
987
988 return $flatOpts;
989 }
990 }
991
992 class HTMLTextField extends HTMLFormField {
993 function getSize() {
994 return isset( $this->mParams['size'] )
995 ? $this->mParams['size']
996 : 45;
997 }
998
999 function getInputHTML( $value ) {
1000 $attribs = array(
1001 'id' => $this->mID,
1002 'name' => $this->mName,
1003 'size' => $this->getSize(),
1004 'value' => $value,
1005 ) + $this->getTooltipAndAccessKey();
1006
1007 if ( isset( $this->mParams['maxlength'] ) ) {
1008 $attribs['maxlength'] = $this->mParams['maxlength'];
1009 }
1010
1011 if ( !empty( $this->mParams['disabled'] ) ) {
1012 $attribs['disabled'] = 'disabled';
1013 }
1014
1015 # TODO: Enforce pattern, step, required, readonly on the server side as
1016 # well
1017 foreach ( array( 'min', 'max', 'pattern', 'title', 'step',
1018 'placeholder' ) as $param ) {
1019 if ( isset( $this->mParams[$param] ) ) {
1020 $attribs[$param] = $this->mParams[$param];
1021 }
1022 }
1023
1024 foreach ( array( 'required', 'autofocus', 'multiple', 'readonly' ) as $param ) {
1025 if ( isset( $this->mParams[$param] ) ) {
1026 $attribs[$param] = '';
1027 }
1028 }
1029
1030 # Implement tiny differences between some field variants
1031 # here, rather than creating a new class for each one which
1032 # is essentially just a clone of this one.
1033 if ( isset( $this->mParams['type'] ) ) {
1034 switch ( $this->mParams['type'] ) {
1035 case 'email':
1036 $attribs['type'] = 'email';
1037 break;
1038 case 'int':
1039 $attribs['type'] = 'number';
1040 break;
1041 case 'float':
1042 $attribs['type'] = 'number';
1043 $attribs['step'] = 'any';
1044 break;
1045 # Pass through
1046 case 'password':
1047 case 'file':
1048 $attribs['type'] = $this->mParams['type'];
1049 break;
1050 }
1051 }
1052
1053 return Html::element( 'input', $attribs );
1054 }
1055 }
1056 class HTMLTextAreaField extends HTMLFormField {
1057 function getCols() {
1058 return isset( $this->mParams['cols'] )
1059 ? $this->mParams['cols']
1060 : 80;
1061 }
1062
1063 function getRows() {
1064 return isset( $this->mParams['rows'] )
1065 ? $this->mParams['rows']
1066 : 25;
1067 }
1068
1069 function getInputHTML( $value ) {
1070 $attribs = array(
1071 'id' => $this->mID,
1072 'name' => $this->mName,
1073 'cols' => $this->getCols(),
1074 'rows' => $this->getRows(),
1075 ) + $this->getTooltipAndAccessKey();
1076
1077
1078 if ( !empty( $this->mParams['disabled'] ) ) {
1079 $attribs['disabled'] = 'disabled';
1080 }
1081
1082 if ( !empty( $this->mParams['readonly'] ) ) {
1083 $attribs['readonly'] = 'readonly';
1084 }
1085
1086 foreach ( array( 'required', 'autofocus' ) as $param ) {
1087 if ( isset( $this->mParams[$param] ) ) {
1088 $attribs[$param] = '';
1089 }
1090 }
1091
1092 return Html::element( 'textarea', $attribs, $value );
1093 }
1094 }
1095
1096 /**
1097 * A field that will contain a numeric value
1098 */
1099 class HTMLFloatField extends HTMLTextField {
1100 function getSize() {
1101 return isset( $this->mParams['size'] )
1102 ? $this->mParams['size']
1103 : 20;
1104 }
1105
1106 function validate( $value, $alldata ) {
1107 $p = parent::validate( $value, $alldata );
1108
1109 if ( $p !== true ) {
1110 return $p;
1111 }
1112
1113 $value = trim( $value );
1114
1115 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#real-numbers
1116 # with the addition that a leading '+' sign is ok.
1117 if ( !preg_match( '/^((\+|\-)?\d+(\.\d+)?(E(\+|\-)?\d+)?)?$/i', $value ) ) {
1118 return wfMsgExt( 'htmlform-float-invalid', 'parse' );
1119 }
1120
1121 # The "int" part of these message names is rather confusing.
1122 # They make equal sense for all numbers.
1123 if ( isset( $this->mParams['min'] ) ) {
1124 $min = $this->mParams['min'];
1125
1126 if ( $min > $value ) {
1127 return wfMsgExt( 'htmlform-int-toolow', 'parse', array( $min ) );
1128 }
1129 }
1130
1131 if ( isset( $this->mParams['max'] ) ) {
1132 $max = $this->mParams['max'];
1133
1134 if ( $max < $value ) {
1135 return wfMsgExt( 'htmlform-int-toohigh', 'parse', array( $max ) );
1136 }
1137 }
1138
1139 return true;
1140 }
1141 }
1142
1143 /**
1144 * A field that must contain a number
1145 */
1146 class HTMLIntField extends HTMLFloatField {
1147 function validate( $value, $alldata ) {
1148 $p = parent::validate( $value, $alldata );
1149
1150 if ( $p !== true ) {
1151 return $p;
1152 }
1153
1154 # http://dev.w3.org/html5/spec/common-microsyntaxes.html#signed-integers
1155 # with the addition that a leading '+' sign is ok. Note that leading zeros
1156 # are fine, and will be left in the input, which is useful for things like
1157 # phone numbers when you know that they are integers (the HTML5 type=tel
1158 # input does not require its value to be numeric). If you want a tidier
1159 # value to, eg, save in the DB, clean it up with intval().
1160 if ( !preg_match( '/^((\+|\-)?\d+)?$/', trim( $value ) )
1161 ) {
1162 return wfMsgExt( 'htmlform-int-invalid', 'parse' );
1163 }
1164
1165 return true;
1166 }
1167 }
1168
1169 /**
1170 * A checkbox field
1171 */
1172 class HTMLCheckField extends HTMLFormField {
1173 function getInputHTML( $value ) {
1174 if ( !empty( $this->mParams['invert'] ) ) {
1175 $value = !$value;
1176 }
1177
1178 $attr = $this->getTooltipAndAccessKey();
1179 $attr['id'] = $this->mID;
1180
1181 if ( !empty( $this->mParams['disabled'] ) ) {
1182 $attr['disabled'] = 'disabled';
1183 }
1184
1185 return Xml::check( $this->mName, $value, $attr ) . '&#160;' .
1186 Html::rawElement( 'label', array( 'for' => $this->mID ), $this->mLabel );
1187 }
1188
1189 /**
1190 * For a checkbox, the label goes on the right hand side, and is
1191 * added in getInputHTML(), rather than HTMLFormField::getRow()
1192 */
1193 function getLabel() {
1194 return '&#160;';
1195 }
1196
1197 function loadDataFromRequest( $request ) {
1198 $invert = false;
1199 if ( isset( $this->mParams['invert'] ) && $this->mParams['invert'] ) {
1200 $invert = true;
1201 }
1202
1203 // GetCheck won't work like we want for checks.
1204 if ( $request->getCheck( 'wpEditToken' ) ) {
1205 // XOR has the following truth table, which is what we want
1206 // INVERT VALUE | OUTPUT
1207 // true true | false
1208 // false true | true
1209 // false false | false
1210 // true false | true
1211 return $request->getBool( $this->mName ) xor $invert;
1212 } else {
1213 return $this->getDefault();
1214 }
1215 }
1216 }
1217
1218 /**
1219 * A select dropdown field. Basically a wrapper for Xmlselect class
1220 */
1221 class HTMLSelectField extends HTMLFormField {
1222 function validate( $value, $alldata ) {
1223 $p = parent::validate( $value, $alldata );
1224
1225 if ( $p !== true ) {
1226 return $p;
1227 }
1228
1229 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1230
1231 if ( in_array( $value, $validOptions ) )
1232 return true;
1233 else
1234 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1235 }
1236
1237 function getInputHTML( $value ) {
1238 $select = new XmlSelect( $this->mName, $this->mID, strval( $value ) );
1239
1240 # If one of the options' 'name' is int(0), it is automatically selected.
1241 # because PHP sucks and things int(0) == 'some string'.
1242 # Working around this by forcing all of them to strings.
1243 foreach( $this->mParams['options'] as $key => &$opt ){
1244 if( is_int( $opt ) ){
1245 $opt = strval( $opt );
1246 }
1247 }
1248 unset( $opt ); # PHP keeps $opt around as a reference, which is a bit scary
1249
1250 if ( !empty( $this->mParams['disabled'] ) ) {
1251 $select->setAttribute( 'disabled', 'disabled' );
1252 }
1253
1254 $select->addOptions( $this->mParams['options'] );
1255
1256 return $select->getHTML();
1257 }
1258 }
1259
1260 /**
1261 * Select dropdown field, with an additional "other" textbox.
1262 */
1263 class HTMLSelectOrOtherField extends HTMLTextField {
1264 static $jsAdded = false;
1265
1266 function __construct( $params ) {
1267 if ( !in_array( 'other', $params['options'], true ) ) {
1268 $params['options'][wfMsg( 'htmlform-selectorother-other' )] = 'other';
1269 }
1270
1271 parent::__construct( $params );
1272 }
1273
1274 static function forceToStringRecursive( $array ) {
1275 if ( is_array( $array ) ) {
1276 return array_map( array( __CLASS__, 'forceToStringRecursive' ), $array );
1277 } else {
1278 return strval( $array );
1279 }
1280 }
1281
1282 function getInputHTML( $value ) {
1283 $valInSelect = false;
1284
1285 if ( $value !== false ) {
1286 $valInSelect = in_array(
1287 $value,
1288 HTMLFormField::flattenOptions( $this->mParams['options'] )
1289 );
1290 }
1291
1292 $selected = $valInSelect ? $value : 'other';
1293
1294 $opts = self::forceToStringRecursive( $this->mParams['options'] );
1295
1296 $select = new XmlSelect( $this->mName, $this->mID, $selected );
1297 $select->addOptions( $opts );
1298
1299 $select->setAttribute( 'class', 'mw-htmlform-select-or-other' );
1300
1301 $tbAttribs = array( 'id' => $this->mID . '-other', 'size' => $this->getSize() );
1302
1303 if ( !empty( $this->mParams['disabled'] ) ) {
1304 $select->setAttribute( 'disabled', 'disabled' );
1305 $tbAttribs['disabled'] = 'disabled';
1306 }
1307
1308 $select = $select->getHTML();
1309
1310 if ( isset( $this->mParams['maxlength'] ) ) {
1311 $tbAttribs['maxlength'] = $this->mParams['maxlength'];
1312 }
1313
1314 $textbox = Html::input(
1315 $this->mName . '-other',
1316 $valInSelect ? '' : $value,
1317 'text',
1318 $tbAttribs
1319 );
1320
1321 return "$select<br />\n$textbox";
1322 }
1323
1324 function loadDataFromRequest( $request ) {
1325 if ( $request->getCheck( $this->mName ) ) {
1326 $val = $request->getText( $this->mName );
1327
1328 if ( $val == 'other' ) {
1329 $val = $request->getText( $this->mName . '-other' );
1330 }
1331
1332 return $val;
1333 } else {
1334 return $this->getDefault();
1335 }
1336 }
1337 }
1338
1339 /**
1340 * Multi-select field
1341 */
1342 class HTMLMultiSelectField extends HTMLFormField {
1343 function validate( $value, $alldata ) {
1344 $p = parent::validate( $value, $alldata );
1345
1346 if ( $p !== true ) {
1347 return $p;
1348 }
1349
1350 if ( !is_array( $value ) ) {
1351 return false;
1352 }
1353
1354 # If all options are valid, array_intersect of the valid options
1355 # and the provided options will return the provided options.
1356 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1357
1358 $validValues = array_intersect( $value, $validOptions );
1359 if ( count( $validValues ) == count( $value ) ) {
1360 return true;
1361 } else {
1362 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1363 }
1364 }
1365
1366 function getInputHTML( $value ) {
1367 $html = $this->formatOptions( $this->mParams['options'], $value );
1368
1369 return $html;
1370 }
1371
1372 function formatOptions( $options, $value ) {
1373 $html = '';
1374
1375 $attribs = array();
1376
1377 if ( !empty( $this->mParams['disabled'] ) ) {
1378 $attribs['disabled'] = 'disabled';
1379 }
1380
1381 foreach ( $options as $label => $info ) {
1382 if ( is_array( $info ) ) {
1383 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1384 $html .= $this->formatOptions( $info, $value );
1385 } else {
1386 $thisAttribs = array( 'id' => "{$this->mID}-$info", 'value' => $info );
1387
1388 $checkbox = Xml::check(
1389 $this->mName . '[]',
1390 in_array( $info, $value, true ),
1391 $attribs + $thisAttribs );
1392 $checkbox .= '&#160;' . Html::rawElement( 'label', array( 'for' => "{$this->mID}-$info" ), $label );
1393
1394 $html .= $checkbox . '<br />';
1395 }
1396 }
1397
1398 return $html;
1399 }
1400
1401 function loadDataFromRequest( $request ) {
1402 # won't work with getCheck
1403 if ( $request->getCheck( 'wpEditToken' ) ) {
1404 $arr = $request->getArray( $this->mName );
1405
1406 if ( !$arr ) {
1407 $arr = array();
1408 }
1409
1410 return $arr;
1411 } else {
1412 return $this->getDefault();
1413 }
1414 }
1415
1416 function getDefault() {
1417 if ( isset( $this->mDefault ) ) {
1418 return $this->mDefault;
1419 } else {
1420 return array();
1421 }
1422 }
1423
1424 protected function needsLabel() {
1425 return false;
1426 }
1427 }
1428
1429 /**
1430 * Radio checkbox fields.
1431 */
1432 class HTMLRadioField extends HTMLFormField {
1433 function validate( $value, $alldata ) {
1434 $p = parent::validate( $value, $alldata );
1435
1436 if ( $p !== true ) {
1437 return $p;
1438 }
1439
1440 if ( !is_string( $value ) && !is_int( $value ) ) {
1441 return false;
1442 }
1443
1444 $validOptions = HTMLFormField::flattenOptions( $this->mParams['options'] );
1445
1446 if ( in_array( $value, $validOptions ) ) {
1447 return true;
1448 } else {
1449 return wfMsgExt( 'htmlform-select-badoption', 'parseinline' );
1450 }
1451 }
1452
1453 /**
1454 * This returns a block of all the radio options, in one cell.
1455 * @see includes/HTMLFormField#getInputHTML()
1456 */
1457 function getInputHTML( $value ) {
1458 $html = $this->formatOptions( $this->mParams['options'], $value );
1459
1460 return $html;
1461 }
1462
1463 function formatOptions( $options, $value ) {
1464 $html = '';
1465
1466 $attribs = array();
1467 if ( !empty( $this->mParams['disabled'] ) ) {
1468 $attribs['disabled'] = 'disabled';
1469 }
1470
1471 # TODO: should this produce an unordered list perhaps?
1472 foreach ( $options as $label => $info ) {
1473 if ( is_array( $info ) ) {
1474 $html .= Html::rawElement( 'h1', array(), $label ) . "\n";
1475 $html .= $this->formatOptions( $info, $value );
1476 } else {
1477 $id = Sanitizer::escapeId( $this->mID . "-$info" );
1478 $html .= Xml::radio(
1479 $this->mName,
1480 $info,
1481 $info == $value,
1482 $attribs + array( 'id' => $id )
1483 );
1484 $html .= '&#160;' .
1485 Html::rawElement( 'label', array( 'for' => $id ), $label );
1486
1487 $html .= "<br />\n";
1488 }
1489 }
1490
1491 return $html;
1492 }
1493
1494 protected function needsLabel() {
1495 return false;
1496 }
1497 }
1498
1499 /**
1500 * An information field (text blob), not a proper input.
1501 */
1502 class HTMLInfoField extends HTMLFormField {
1503 function __construct( $info ) {
1504 $info['nodata'] = true;
1505
1506 parent::__construct( $info );
1507 }
1508
1509 function getInputHTML( $value ) {
1510 return !empty( $this->mParams['raw'] ) ? $value : htmlspecialchars( $value );
1511 }
1512
1513 function getTableRow( $value ) {
1514 if ( !empty( $this->mParams['rawrow'] ) ) {
1515 return $value;
1516 }
1517
1518 return parent::getTableRow( $value );
1519 }
1520
1521 protected function needsLabel() {
1522 return false;
1523 }
1524 }
1525
1526 class HTMLHiddenField extends HTMLFormField {
1527 public function __construct( $params ) {
1528 parent::__construct( $params );
1529
1530 # Per HTML5 spec, hidden fields cannot be 'required'
1531 # http://dev.w3.org/html5/spec/states-of-the-type-attribute.html#hidden-state
1532 unset( $this->mParams['required'] );
1533 }
1534
1535 public function getTableRow( $value ) {
1536 $params = array();
1537 if ( $this->mID ) {
1538 $params['id'] = $this->mID;
1539 }
1540
1541 $this->mParent->addHiddenField(
1542 $this->mName,
1543 $this->mDefault,
1544 $params
1545 );
1546
1547 return '';
1548 }
1549
1550 public function getInputHTML( $value ) { return ''; }
1551 }
1552
1553 /**
1554 * Add a submit button inline in the form (as opposed to
1555 * HTMLForm::addButton(), which will add it at the end).
1556 */
1557 class HTMLSubmitField extends HTMLFormField {
1558
1559 function __construct( $info ) {
1560 $info['nodata'] = true;
1561 parent::__construct( $info );
1562 }
1563
1564 function getInputHTML( $value ) {
1565 return Xml::submitButton(
1566 $value,
1567 array(
1568 'class' => 'mw-htmlform-submit',
1569 'name' => $this->mName,
1570 'id' => $this->mID,
1571 )
1572 );
1573 }
1574
1575 protected function needsLabel() {
1576 return false;
1577 }
1578
1579 /**
1580 * Button cannot be invalid
1581 */
1582 public function validate( $value, $alldata ){
1583 return true;
1584 }
1585 }
1586
1587 class HTMLEditTools extends HTMLFormField {
1588 public function getInputHTML( $value ) {
1589 return '';
1590 }
1591
1592 public function getTableRow( $value ) {
1593 return "<tr><td></td><td class=\"mw-input\">"
1594 . '<div class="mw-editTools">'
1595 . wfMsgExt( empty( $this->mParams['message'] )
1596 ? 'edittools' : $this->mParams['message'],
1597 array( 'parse', 'content' ) )
1598 . "</div></td></tr>\n";
1599 }
1600 }