3 * Methods to generate XML.
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.
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.
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
23 use MediaWiki\MediaWikiServices
;
26 * Module of static functions for generating XML
30 * Format an XML element with given attributes and, optionally, text content.
31 * Element and attribute names are assumed to be ready for literal inclusion.
32 * Strings are assumed to not contain XML-illegal characters; special
33 * characters (<, >, &) are escaped but illegals are not touched.
35 * @param string $element Element name
36 * @param array|null $attribs Name=>value pairs. Values will be escaped.
37 * @param string $contents Null to make an open tag only; '' for a contentless closed tag (default)
38 * @param bool $allowShortTag Whether '' in $contents will result in a contentless closed tag
41 public static function element( $element, $attribs = null, $contents = '',
44 $out = '<' . $element;
45 if ( !is_null( $attribs ) ) {
46 $out .= self
::expandAttributes( $attribs );
48 if ( is_null( $contents ) ) {
51 if ( $allowShortTag && $contents === '' ) {
54 $out .= '>' . htmlspecialchars( $contents, ENT_NOQUOTES
) . "</$element>";
61 * Given an array of ('attributename' => 'value'), it generates the code
62 * to set the XML attributes : attributename="value".
63 * The values are passed to Sanitizer::encodeAttribute.
64 * Returns null or empty string if no attributes given.
65 * @param array|null $attribs Array of attributes for an XML element
69 public static function expandAttributes( $attribs ) {
71 if ( is_null( $attribs ) ) {
73 } elseif ( is_array( $attribs ) ) {
74 foreach ( $attribs as $name => $val ) {
75 $out .= " {$name}=\"" . Sanitizer
::encodeAttribute( $val ) . '"';
79 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__
);
84 * Format an XML element as with self::element(), but run text through the content language's
85 * normalize() validator first to ensure that no invalid UTF-8 is passed.
87 * @param string $element
88 * @param array $attribs Name=>value pairs. Values will be escaped.
89 * @param string $contents Null to make an open tag only; '' for a contentless closed tag (default)
92 public static function elementClean( $element, $attribs = [], $contents = '' ) {
94 $attribs = array_map( [ 'UtfNormal\Validator', 'cleanUp' ], $attribs );
98 MediaWikiServices
::getInstance()->getContentLanguage()->normalize( $contents );
100 return self
::element( $element, $attribs, $contents );
104 * This opens an XML element
106 * @param string $element Name of the element
107 * @param array|null $attribs Array of attributes, see Xml::expandAttributes()
110 public static function openElement( $element, $attribs = null ) {
111 return '<' . $element . self
::expandAttributes( $attribs ) . '>';
115 * Shortcut to close an XML element
116 * @param string $element Element name
119 public static function closeElement( $element ) {
120 return "</$element>";
124 * Same as Xml::element(), but does not escape contents. Handy when the
125 * content you have is already valid xml.
127 * @param string $element Element name
128 * @param array|null $attribs Array of attributes
129 * @param string $contents Content of the element
132 public static function tags( $element, $attribs, $contents ) {
133 return self
::openElement( $element, $attribs ) . $contents . "</$element>";
137 * Create a date selector
139 * @param string $selected The month which should be selected, default ''.
140 * @param string|null $allmonths Value of a special item denoting all month.
141 * Null to not include (default).
142 * @param string $id Element identifier
143 * @return string Html string containing the month selector
145 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
148 $data = new XmlSelect( 'month', $id, $selected );
149 if ( is_null( $selected ) ) {
152 if ( !is_null( $allmonths ) ) {
153 $options[wfMessage( 'monthsall' )->text()] = $allmonths;
155 for ( $i = 1; $i < 13; $i++
) {
156 $options[$wgLang->getMonthName( $i )] = $i;
158 $data->addOptions( $options );
159 $data->setAttribute( 'class', 'mw-month-selector' );
160 return $data->getHTML();
164 * @param int|string $year Use '' or 0 to start with no year preselected.
165 * @param int|string $month A month in the 1..12 range. Use '', 0 or -1 to start with no month
167 * @return string Formatted HTML
169 public static function dateMenu( $year, $month ) {
170 # Offset overrides year/month selection
171 if ( $month && $month !== -1 ) {
172 $encMonth = intval( $month );
177 $encYear = intval( $year );
178 } elseif ( $encMonth ) {
179 $timestamp = MWTimestamp
::getInstance();
180 $thisMonth = intval( $timestamp->format( 'n' ) );
181 $thisYear = intval( $timestamp->format( 'Y' ) );
182 if ( intval( $encMonth ) > $thisMonth ) {
185 $encYear = $thisYear;
189 $inputAttribs = [ 'id' => 'year', 'maxlength' => 4, 'size' => 7 ];
190 return self
::label( wfMessage( 'year' )->text(), 'year' ) . ' ' .
191 Html
::input( 'year', $encYear, 'number', $inputAttribs ) . ' ' .
192 self
::label( wfMessage( 'month' )->text(), 'month' ) . ' ' .
193 self
::monthSelector( $encMonth, -1 );
197 * Construct a language selector appropriate for use in a form or preferences
199 * @param string $selected The language code of the selected language
200 * @param bool $customisedOnly If true only languages which have some content are listed
201 * @param string|null $inLanguage The ISO code of the language to display the select list in
202 * @param array $overrideAttrs Override the attributes of the select tag (since 1.20)
203 * @param Message|null $msg Label message key (since 1.20)
204 * @return array Array containing 2 items: label HTML and select list HTML
206 public static function languageSelector( $selected, $customisedOnly = true,
207 $inLanguage = null, $overrideAttrs = [], Message
$msg = null
209 global $wgLanguageCode;
211 $include = $customisedOnly ?
'mwfile' : 'mw';
212 $languages = Language
::fetchLanguageNames( $inLanguage, $include );
214 // Make sure the site language is in the list;
215 // a custom language code might not have a defined name...
216 if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
217 $languages[$wgLanguageCode] = $wgLanguageCode;
218 // Sort the array again
223 * If a bogus value is set, default to the content language.
224 * Otherwise, no default is selected and the user ends up
225 * with Afrikaans since it's first in the list.
227 $selected = isset( $languages[$selected] ) ?
$selected : $wgLanguageCode;
229 foreach ( $languages as $code => $name ) {
230 $options .= self
::option( "$code - $name", $code, $code == $selected ) . "\n";
233 $attrs = [ 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ];
234 $attrs = array_merge( $attrs, $overrideAttrs );
236 if ( $msg === null ) {
237 $msg = wfMessage( 'yourlanguage' );
240 self
::label( $msg->text(), $attrs['id'] ),
241 self
::tags( 'select', $attrs, $options )
246 * Shortcut to make a span element
247 * @param string $text Content of the element, will be escaped
248 * @param string $class Class name of the span element
249 * @param array $attribs Other attributes
252 public static function span( $text, $class, $attribs = [] ) {
253 return self
::element( 'span', [ 'class' => $class ] +
$attribs, $text );
257 * Shortcut to make a specific element with a class attribute
258 * @param string $text Content of the element, will be escaped
259 * @param string $class Class name of the span element
260 * @param string $tag Element name
261 * @param array $attribs Other attributes
264 public static function wrapClass( $text, $class, $tag = 'span', $attribs = [] ) {
265 return self
::tags( $tag, [ 'class' => $class ] +
$attribs, $text );
269 * Convenience function to build an HTML text input field
270 * @param string $name Value of the name attribute
271 * @param int $size Value of the size attribute
272 * @param mixed $value Value of the value attribute
273 * @param array $attribs Other attributes
274 * @return string HTML
276 public static function input( $name, $size = false, $value = false, $attribs = [] ) {
277 $attributes = [ 'name' => $name ];
280 $attributes['size'] = $size;
283 if ( $value !== false ) { // maybe 0
284 $attributes['value'] = $value;
287 return self
::element( 'input',
288 Html
::getTextInputAttributes( $attributes +
$attribs ) );
292 * Convenience function to build an HTML password input field
293 * @param string $name Value of the name attribute
294 * @param int $size Value of the size attribute
295 * @param mixed $value Value of the value attribute
296 * @param array $attribs Other attributes
297 * @return string HTML
299 public static function password( $name, $size = false, $value = false,
302 return self
::input( $name, $size, $value,
303 array_merge( $attribs, [ 'type' => 'password' ] ) );
307 * Internal function for use in checkboxes and radio buttons and such.
309 * @param string $name
310 * @param bool $present
314 public static function attrib( $name, $present = true ) {
315 return $present ?
[ $name => $name ] : [];
319 * Convenience function to build an HTML checkbox
320 * @param string $name Value of the name attribute
321 * @param bool $checked Whether the checkbox is checked or not
322 * @param array $attribs Array other attributes
323 * @return string HTML
325 public static function check( $name, $checked = false, $attribs = [] ) {
326 return self
::element( 'input', array_merge(
329 'type' => 'checkbox',
331 self
::attrib( 'checked', $checked ),
336 * Convenience function to build an HTML radio button
337 * @param string $name Value of the name attribute
338 * @param string $value Value of the value attribute
339 * @param bool $checked Whether the checkbox is checked or not
340 * @param array $attribs Other attributes
341 * @return string HTML
343 public static function radio( $name, $value, $checked = false, $attribs = [] ) {
344 return self
::element( 'input', [
347 'value' => $value ] + self
::attrib( 'checked', $checked ) +
$attribs );
351 * Convenience function to build an HTML form label
352 * @param string $label Text of the label
354 * @param array $attribs An attribute array. This will usually be
355 * the same array as is passed to the corresponding input element,
356 * so this function will cherry-pick appropriate attributes to
357 * apply to the label as well; only class and title are applied.
358 * @return string HTML
360 public static function label( $label, $id, $attribs = [] ) {
361 $a = [ 'for' => $id ];
363 foreach ( [ 'class', 'title' ] as $attr ) {
364 if ( isset( $attribs[$attr] ) ) {
365 $a[$attr] = $attribs[$attr];
369 return self
::element( 'label', $a, $label );
373 * Convenience function to build an HTML text input field with a label
374 * @param string $label Text of the label
375 * @param string $name Value of the name attribute
376 * @param string $id Id of the input
377 * @param int|bool $size Value of the size attribute
378 * @param string|bool $value Value of the value attribute
379 * @param array $attribs Other attributes
380 * @return string HTML
382 public static function inputLabel( $label, $name, $id, $size = false,
383 $value = false, $attribs = []
385 list( $label, $input ) = self
::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
386 return $label . "\u{00A0}" . $input;
390 * Same as Xml::inputLabel() but return input and label in an array
392 * @param string $label
393 * @param string $name
395 * @param int|bool $size
396 * @param string|bool $value
397 * @param array $attribs
401 public static function inputLabelSep( $label, $name, $id, $size = false,
402 $value = false, $attribs = []
405 self
::label( $label, $id, $attribs ),
406 self
::input( $name, $size, $value, [ 'id' => $id ] +
$attribs )
411 * Convenience function to build an HTML checkbox with a label
413 * @param string $label
414 * @param string $name
416 * @param bool $checked
417 * @param array $attribs
419 * @return string HTML
421 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = [] ) {
422 global $wgUseMediaWikiUIEverywhere;
423 $chkLabel = self
::check( $name, $checked, [ 'id' => $id ] +
$attribs ) .
425 self
::label( $label, $id, $attribs );
427 if ( $wgUseMediaWikiUIEverywhere ) {
428 $chkLabel = self
::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
429 $chkLabel . self
::closeElement( 'div' );
435 * Convenience function to build an HTML radio button with a label
437 * @param string $label
438 * @param string $name
439 * @param string $value
441 * @param bool $checked
442 * @param array $attribs
444 * @return string HTML
446 public static function radioLabel( $label, $name, $value, $id,
447 $checked = false, $attribs = []
449 return self
::radio( $name, $value, $checked, [ 'id' => $id ] +
$attribs ) .
451 self
::label( $label, $id, $attribs );
455 * Convenience function to build an HTML submit button
456 * When $wgUseMediaWikiUIEverywhere is true it will default to a progressive button
457 * @param string $value Label text for the button (unescaped)
458 * @param array $attribs Optional custom attributes
459 * @return string HTML
461 public static function submitButton( $value, $attribs = [] ) {
462 global $wgUseMediaWikiUIEverywhere;
467 // Done conditionally for time being as it is possible
469 // might need to be mw-ui-destructive (e.g. delete a page)
470 if ( $wgUseMediaWikiUIEverywhere ) {
471 $baseAttrs['class'] = 'mw-ui-button mw-ui-progressive';
473 // Any custom attributes will take precendence of anything in baseAttrs e.g. override the class
474 $attribs = $attribs +
$baseAttrs;
475 return Html
::element( 'input', $attribs );
479 * Convenience function to build an HTML drop-down list item.
480 * @param string $text Text for this item. Will be HTML escaped
481 * @param string|null $value Form submission value; if empty, use text
482 * @param bool $selected If true, will be the default selected item
483 * @param array $attribs Optional additional HTML attributes
484 * @return string HTML
486 public static function option( $text, $value = null, $selected = false,
488 if ( !is_null( $value ) ) {
489 $attribs['value'] = $value;
492 $attribs['selected'] = 'selected';
494 return Html
::element( 'option', $attribs, $text );
498 * Build a drop-down box from a textual list. This is a wrapper
499 * for Xml::listDropDownOptions() plus the XmlSelect class.
501 * @param string $name Name and id for the drop-down
502 * @param string $list Correctly formatted text (newline delimited) to be
503 * used to generate the options.
504 * @param string $other Text for the "Other reasons" option
505 * @param string $selected Option which should be pre-selected
506 * @param string $class CSS classes for the drop-down
507 * @param int|null $tabindex Value of the tabindex attribute
510 public static function listDropDown( $name = '', $list = '', $other = '',
511 $selected = '', $class = '', $tabindex = null
513 $options = self
::listDropDownOptions( $list, [ 'other' => $other ] );
515 $xmlSelect = new XmlSelect( $name, $name, $selected );
516 $xmlSelect->addOptions( $options );
519 $xmlSelect->setAttribute( 'class', $class );
522 $xmlSelect->setAttribute( 'tabindex', $tabindex );
525 return $xmlSelect->getHTML();
529 * Build options for a drop-down box from a textual list.
531 * The result of this function can be passed to XmlSelect::addOptions()
532 * (to render a plain `<select>` dropdown box) or to Xml::listDropDownOptionsOoui()
533 * and then OOUI\DropdownInputWidget() (to render a pretty one).
535 * @param string $list Correctly formatted text (newline delimited) to be
536 * used to generate the options.
537 * @param array $params Extra parameters:
538 * - string $params['other'] If set, add an option with this as text and a value of 'other'
539 * @return array Array keys are textual labels, values are internal values
541 public static function listDropDownOptions( $list, $params = [] ) {
544 if ( isset( $params['other'] ) ) {
545 $options[ $params['other'] ] = 'other';
549 foreach ( explode( "\n", $list ) as $option ) {
550 $value = trim( $option );
551 if ( $value == '' ) {
553 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
554 # A new group is starting...
555 $value = trim( substr( $value, 1 ) );
557 } elseif ( substr( $value, 0, 2 ) == '**' ) {
559 $opt = trim( substr( $value, 2 ) );
560 if ( $optgroup === false ) {
561 $options[$opt] = $opt;
563 $options[$optgroup][$opt] = $opt;
566 # groupless reason list
568 $options[$option] = $option;
576 * Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
578 * TODO Find a better home for this function.
580 * @param array $options Options, as returned e.g. by Xml::listDropDownOptions()
583 public static function listDropDownOptionsOoui( $options ) {
586 foreach ( $options as $text => $value ) {
587 if ( is_array( $value ) ) {
588 $optionsOoui[] = [ 'optgroup' => (string)$text ];
589 foreach ( $value as $text2 => $value2 ) {
590 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
593 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
601 * Shortcut for creating fieldsets.
603 * @param string|bool $legend Legend of the fieldset. If evaluates to false,
604 * legend is not added.
605 * @param string $content Pre-escaped content for the fieldset. If false,
606 * only open fieldset is returned.
607 * @param array $attribs Any attributes to fieldset-element.
611 public static function fieldset( $legend = false, $content = false, $attribs = [] ) {
612 $s = self
::openElement( 'fieldset', $attribs ) . "\n";
615 $s .= self
::element( 'legend', null, $legend ) . "\n";
618 if ( $content !== false ) {
619 $s .= $content . "\n";
620 $s .= self
::closeElement( 'fieldset' ) . "\n";
627 * Shortcut for creating textareas.
629 * @param string $name The 'name' for the textarea
630 * @param string $content Content for the textarea
631 * @param int $cols The number of columns for the textarea
632 * @param int $rows The number of rows for the textarea
633 * @param array $attribs Any other attributes for the textarea
637 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = [] ) {
638 return self
::element( 'textarea',
639 Html
::getTextInputAttributes(
651 * Encode a variable of arbitrary type to JavaScript.
652 * If the value is an XmlJsCode object, pass through the object's value verbatim.
654 * @note Only use this function for generating JavaScript code. If generating output
655 * for a proper JSON parser, just call FormatJson::encode() directly.
657 * @param mixed $value The value being encoded. Can be any type except a resource.
658 * @param bool $pretty If true, add non-significant whitespace to improve readability.
659 * @return string|bool String if successful; false upon failure
661 public static function encodeJsVar( $value, $pretty = false ) {
662 if ( $value instanceof XmlJsCode
) {
663 return $value->value
;
665 return FormatJson
::encode( $value, $pretty, FormatJson
::UTF8_OK
);
669 * Create a call to a JavaScript function. The supplied arguments will be
670 * encoded using Xml::encodeJsVar().
673 * @param string $name The name of the function to call, or a JavaScript expression
674 * which evaluates to a function object which is called.
675 * @param array $args The arguments to pass to the function.
676 * @param bool $pretty If true, add non-significant whitespace to improve readability.
677 * @return string|bool String if successful; false upon failure
679 public static function encodeJsCall( $name, $args, $pretty = false ) {
680 foreach ( $args as &$arg ) {
681 $arg = self
::encodeJsVar( $arg, $pretty );
682 if ( $arg === false ) {
687 return "$name(" . ( $pretty
688 ?
( ' ' . implode( ', ', $args ) . ' ' )
689 : implode( ',', $args )
694 * Check if a string is well-formed XML.
695 * Must include the surrounding tag.
696 * This function is a DoS vector if an attacker can define
699 * @param string $text String to test.
702 * @todo Error position reporting return
704 private static function isWellFormed( $text ) {
705 $parser = xml_parser_create( "UTF-8" );
707 # case folding violates XML standard, turn it off
708 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
710 if ( !xml_parse( $parser, $text, true ) ) {
711 // $err = xml_error_string( xml_get_error_code( $parser ) );
712 // $position = xml_get_current_byte_index( $parser );
713 // $fragment = $this->extractFragment( $html, $position );
714 // $this->mXmlError = "$err at byte $position:\n$fragment";
715 xml_parser_free( $parser );
719 xml_parser_free( $parser );
725 * Check if a string is a well-formed XML fragment.
726 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
727 * and can use HTML named entities.
729 * @param string $text
732 public static function isWellFormedXmlFragment( $text ) {
734 Sanitizer
::hackDocType() .
739 return self
::isWellFormed( $html );
743 * Replace " > and < with their respective HTML entities ( ",
746 * @param string $in Text that might contain HTML tags.
747 * @return string Escaped string
749 public static function escapeTagsOnly( $in ) {
752 [ '"', '>', '<' ],
757 * Generate a form (without the opening form element).
758 * Output optionally includes a submit button.
759 * @param array $fields Associative array, key is the name of a message that
760 * contains a description for the field, value is an HTML string
761 * containing the appropriate input.
762 * @param string|null $submitLabel The name of a message containing a label for
764 * @param array $submitAttribs The attributes to add to the submit button
765 * @return string HTML form.
767 public static function buildForm( $fields, $submitLabel = null, $submitAttribs = [] ) {
769 $form .= "<table><tbody>";
771 foreach ( $fields as $labelmsg => $input ) {
772 $id = "mw-$labelmsg";
773 $form .= self
::openElement( 'tr', [ 'id' => $id ] );
775 // TODO use a <label> here for accessibility purposes - will need
776 // to either not use a table to build the form, or find the ID of
777 // the input somehow.
779 $form .= self
::tags( 'td', [ 'class' => 'mw-label' ], wfMessage( $labelmsg )->parse() );
780 $form .= self
::openElement( 'td', [ 'class' => 'mw-input' ] )
781 . $input . self
::closeElement( 'td' );
782 $form .= self
::closeElement( 'tr' );
785 if ( $submitLabel ) {
786 $form .= self
::openElement( 'tr' );
787 $form .= self
::tags( 'td', [], '' );
788 $form .= self
::openElement( 'td', [ 'class' => 'mw-submit' ] )
789 . self
::submitButton( wfMessage( $submitLabel )->text(), $submitAttribs )
790 . self
::closeElement( 'td' );
791 $form .= self
::closeElement( 'tr' );
794 $form .= "</tbody></table>";
800 * Build a table of data
801 * @param array $rows An array of arrays of strings, each to be a row in a table
802 * @param array $attribs An array of attributes to apply to the table tag [optional]
803 * @param array|null $headers An array of strings to use as table headers [optional]
806 public static function buildTable( $rows, $attribs = [], $headers = null ) {
807 $s = self
::openElement( 'table', $attribs );
809 if ( is_array( $headers ) ) {
810 $s .= self
::openElement( 'thead', $attribs );
812 foreach ( $headers as $id => $header ) {
815 if ( is_string( $id ) ) {
816 $attribs['id'] = $id;
819 $s .= self
::element( 'th', $attribs, $header );
821 $s .= self
::closeElement( 'thead' );
824 foreach ( $rows as $id => $row ) {
827 if ( is_string( $id ) ) {
828 $attribs['id'] = $id;
831 $s .= self
::buildTableRow( $attribs, $row );
834 $s .= self
::closeElement( 'table' );
840 * Build a row for a table
841 * @param array $attribs An array of attributes to apply to the tr tag
842 * @param array $cells An array of strings to put in <td>
845 public static function buildTableRow( $attribs, $cells ) {
846 $s = self
::openElement( 'tr', $attribs );
848 foreach ( $cells as $id => $cell ) {
851 if ( is_string( $id ) ) {
852 $attribs['id'] = $id;
855 $s .= self
::element( 'td', $attribs, $cell );
858 $s .= self
::closeElement( 'tr' );