4 * Module of static functions for generating XML
9 * Format an XML element with given attributes and, optionally, text content.
10 * Element and attribute names are assumed to be ready for literal inclusion.
11 * Strings are assumed to not contain XML-illegal characters; special
12 * characters (<, >, &) are escaped but illegals are not touched.
14 * @param $element String: element name
15 * @param $attribs Array: Name=>value pairs. Values will be escaped.
16 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
17 * @param $allowShortTag Bool: whether '' in $contents will result in a contentless closed tag
20 public static function element( $element, $attribs = null, $contents = '', $allowShortTag = true ) {
21 $out = '<' . $element;
22 if( !is_null( $attribs ) ) {
23 $out .= self
::expandAttributes( $attribs );
25 if( is_null( $contents ) ) {
28 if( $allowShortTag && $contents === '' ) {
31 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
38 * Given an array of ('attributename' => 'value'), it generates the code
39 * to set the XML attributes : attributename="value".
40 * The values are passed to Sanitizer::encodeAttribute.
41 * Return null if no attributes given.
42 * @param $attribs Array of attributes for an XML element
44 public static function expandAttributes( $attribs ) {
46 if( is_null( $attribs ) ) {
48 } elseif( is_array( $attribs ) ) {
49 foreach( $attribs as $name => $val ) {
50 $out .= " {$name}=\"" . Sanitizer
::encodeAttribute( $val ) . '"';
54 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__
);
59 * Format an XML element as with self::element(), but run text through the
60 * $wgContLang->normalize() validator first to ensure that no invalid UTF-8
63 * @param $element String:
64 * @param $attribs Array: Name=>value pairs. Values will be escaped.
65 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
68 public static function elementClean( $element, $attribs = array(), $contents = '') {
71 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
74 wfProfileIn( __METHOD__
. '-norm' );
75 $contents = $wgContLang->normalize( $contents );
76 wfProfileOut( __METHOD__
. '-norm' );
78 return self
::element( $element, $attribs, $contents );
82 * This opens an XML element
84 * @param $element String name of the element
85 * @param $attribs array of attributes, see Xml::expandAttributes()
88 public static function openElement( $element, $attribs = null ) {
89 return '<' . $element . self
::expandAttributes( $attribs ) . '>';
93 * Shortcut to close an XML element
94 * @param $element String element name
97 public static function closeElement( $element ) { return "</$element>"; }
100 * Same as Xml::element(), but does not escape contents. Handy when the
101 * content you have is already valid xml.
103 * @param $element String element name
104 * @param $attribs array of attributes
105 * @param $contents String content of the element
108 public static function tags( $element, $attribs = null, $contents ) {
109 return self
::openElement( $element, $attribs ) . $contents . "</$element>";
113 * Build a drop-down box for selecting a namespace
115 * @param $selected Mixed: Namespace which should be pre-selected
116 * @param $all Mixed: Value of an item denoting all namespaces, or null to omit
117 * @param $element_name String: value of the "name" attribute of the select tag
118 * @param $label String: optional label to add to the field
120 * @deprecated since 1.19
122 public static function namespaceSelector( $selected = '', $all = null, $element_name = 'namespace', $label = null ) {
123 wfDeprecated( __METHOD__
, '1.19' );
124 return Html
::namespaceSelector( array(
125 'selected' => $selected,
129 'name' => $element_name,
131 'class' => 'namespaceselector',
136 * Create a date selector
138 * @param $selected Mixed: the month which should be selected, default ''
139 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
140 * @param $id String: Element identifier
141 * @return String: Html string containing the month selector
143 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
146 if( is_null( $selected ) )
148 if( !is_null( $allmonths ) )
149 $options[] = self
::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
150 for( $i = 1; $i < 13; $i++
)
151 $options[] = self
::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
152 return self
::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
153 . implode( "\n", $options )
154 . self
::closeElement( 'select' );
158 * @param $year Integer
159 * @param $month Integer
160 * @return string Formatted HTML
162 public static function dateMenu( $year, $month ) {
163 # Offset overrides year/month selection
164 if( $month && $month !== -1 ) {
165 $encMonth = intval( $month );
170 $encYear = intval( $year );
171 } elseif( $encMonth ) {
172 $thisMonth = intval( gmdate( 'n' ) );
173 $thisYear = intval( gmdate( 'Y' ) );
174 if( intval($encMonth) > $thisMonth ) {
177 $encYear = $thisYear;
181 return Xml
::label( wfMsg( 'year' ), 'year' ) . ' '.
182 Xml
::input( 'year', 4, $encYear, array('id' => 'year', 'maxlength' => 4) ) . ' '.
183 Xml
::label( wfMsg( 'month' ), 'month' ) . ' '.
184 Xml
::monthSelector( $encMonth, -1 );
188 * Construct a language selector appropriate for use in a form or preferences
190 * @param string $selected The language code of the selected language
191 * @param boolean $customisedOnly If true only languages which have some content are listed
192 * @param string $language The ISO code of the language to display the select list in (optional)
193 * @return array containing 2 items: label HTML and select list HTML
195 public static function languageSelector( $selected, $customisedOnly = true, $language = null ) {
196 global $wgLanguageCode;
198 // If a specific language was requested and CLDR is installed, use it
199 if ( $language && is_callable( array( 'LanguageNames', 'getNames' ) ) ) {
200 if ( $customisedOnly ) {
201 $listType = LanguageNames
::LIST_MW_SUPPORTED
; // Only pull names that have localisation in MediaWiki
203 $listType = LanguageNames
::LIST_MW
; // Pull all languages that are in Names.php
205 // Retrieve the list of languages in the requested language (via CLDR)
206 $languages = LanguageNames
::getNames(
207 $language, // Code of the requested language
208 LanguageNames
::FALLBACK_NORMAL
, // Use fallback chain
212 $languages = Language
::getLanguageNames( $customisedOnly );
215 // Make sure the site language is in the list; a custom language code might not have a
217 if( !array_key_exists( $wgLanguageCode, $languages ) ) {
218 $languages[$wgLanguageCode] = $wgLanguageCode;
224 * If a bogus value is set, default to the content language.
225 * Otherwise, no default is selected and the user ends up
226 * with an Afrikaans interface since it's first in the list.
228 $selected = isset( $languages[$selected] ) ?
$selected : $wgLanguageCode;
230 foreach( $languages as $code => $name ) {
231 $options .= Xml
::option( "$code - $name", $code, ($code == $selected) ) . "\n";
235 Xml
::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
237 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
245 * Shortcut to make a span element
246 * @param $text String content of the element, will be escaped
247 * @param $class String class name of the span element
248 * @param $attribs array other attributes
251 public static function span( $text, $class, $attribs = array() ) {
252 return self
::element( 'span', array( 'class' => $class ) +
$attribs, $text );
256 * Shortcut to make a specific element with a class attribute
257 * @param $text string content of the element, will be escaped
258 * @param $class string class name of the span element
259 * @param $tag string element name
260 * @param $attribs array other attributes
263 public static function wrapClass( $text, $class, $tag = 'span', $attribs = array() ) {
264 return self
::tags( $tag, array( 'class' => $class ) +
$attribs, $text );
268 * Convenience function to build an HTML text input field
269 * @param $name String value of the name attribute
270 * @param $size int value of the size attribute
271 * @param $value mixed value of the value attribute
272 * @param $attribs array other attributes
273 * @return string HTML
275 public static function input( $name, $size = false, $value = false, $attribs = array() ) {
276 $attributes = array( 'name' => $name );
279 $attributes['size'] = $size;
282 if( $value !== false ) { // maybe 0
283 $attributes['value'] = $value;
286 return self
::element( 'input', $attributes +
$attribs );
290 * Convenience function to build an HTML password input field
291 * @param $name string value of the name attribute
292 * @param $size int value of the size attribute
293 * @param $value mixed value of the value attribute
294 * @param $attribs array other attributes
295 * @return string HTML
297 public static function password( $name, $size = false, $value = false, $attribs = array() ) {
298 return self
::input( $name, $size, $value, array_merge( $attribs, array( 'type' => 'password' ) ) );
302 * Internal function for use in checkboxes and radio buttons and such.
304 * @param $name string
305 * @param $present bool
309 public static function attrib( $name, $present = true ) {
310 return $present ?
array( $name => $name ) : array();
314 * Convenience function to build an HTML checkbox
315 * @param $name String value of the name attribute
316 * @param $checked Bool Whether the checkbox is checked or not
317 * @param $attribs Array other attributes
318 * @return string HTML
320 public static function check( $name, $checked = false, $attribs=array() ) {
321 return self
::element( 'input', array_merge(
324 'type' => 'checkbox',
326 self
::attrib( 'checked', $checked ),
331 * Convenience function to build an HTML radio button
332 * @param $name String value of the name attribute
333 * @param $value String value of the value attribute
334 * @param $checked Bool Whether the checkbox is checked or not
335 * @param $attribs Array other attributes
336 * @return string HTML
338 public static function radio( $name, $value, $checked = false, $attribs = array() ) {
339 return self
::element( 'input', array(
342 'value' => $value ) + self
::attrib( 'checked', $checked ) +
$attribs );
346 * Convenience function to build an HTML form label
347 * @param $label String text of the label
349 * @param $attribs Array an attribute array. This will usuall be
350 * the same array as is passed to the corresponding input element,
351 * so this function will cherry-pick appropriate attributes to
352 * apply to the label as well; only class and title are applied.
353 * @return string HTML
355 public static function label( $label, $id, $attribs = array() ) {
356 $a = array( 'for' => $id );
358 # FIXME avoid copy pasting below:
359 if( isset( $attribs['class'] ) ){
360 $a['class'] = $attribs['class'];
362 if( isset( $attribs['title'] ) ){
363 $a['title'] = $attribs['title'];
366 return self
::element( 'label', $a, $label );
370 * Convenience function to build an HTML text input field with a label
371 * @param $label String text of the label
372 * @param $name String value of the name attribute
373 * @param $id String id of the input
374 * @param $size Int|Bool value of the size attribute
375 * @param $value String|Bool value of the value attribute
376 * @param $attribs array other attributes
377 * @return string HTML
379 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs = array() ) {
380 list( $label, $input ) = self
::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
381 return $label . ' ' . $input;
385 * Same as Xml::inputLabel() but return input and label in an array
387 * @param $label String
388 * @param $name String
390 * @param $size Int|Bool
391 * @param $value String|Bool
392 * @param $attribs array
396 public static function inputLabelSep( $label, $name, $id, $size = false, $value = false, $attribs = array() ) {
398 Xml
::label( $label, $id, $attribs ),
399 self
::input( $name, $size, $value, array( 'id' => $id ) +
$attribs )
404 * Convenience function to build an HTML checkbox with a label
409 * @param $checked bool
410 * @param $attribs array
412 * @return string HTML
414 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = array() ) {
415 return self
::check( $name, $checked, array( 'id' => $id ) +
$attribs ) .
417 self
::label( $label, $id, $attribs );
421 * Convenience function to build an HTML radio button with a label
427 * @param $checked bool
428 * @param $attribs array
430 * @return string HTML
432 public static function radioLabel( $label, $name, $value, $id, $checked = false, $attribs = array() ) {
433 return self
::radio( $name, $value, $checked, array( 'id' => $id ) +
$attribs ) .
435 self
::label( $label, $id, $attribs );
439 * Convenience function to build an HTML submit button
440 * @param $value String: label text for the button
441 * @param $attribs Array: optional custom attributes
442 * @return string HTML
444 public static function submitButton( $value, $attribs = array() ) {
445 return Html
::element( 'input', array( 'type' => 'submit', 'value' => $value ) +
$attribs );
449 * Convenience function to build an HTML drop-down list item.
450 * @param $text String: text for this item
451 * @param $value String: form submission value; if empty, use text
452 * @param $selected boolean: if true, will be the default selected item
453 * @param $attribs array: optional additional HTML attributes
454 * @return string HTML
456 public static function option( $text, $value=null, $selected = false,
457 $attribs = array() ) {
458 if( !is_null( $value ) ) {
459 $attribs['value'] = $value;
462 $attribs['selected'] = 'selected';
464 return Html
::element( 'option', $attribs, $text );
468 * Build a drop-down box from a textual list.
470 * @param $name Mixed: Name and id for the drop-down
471 * @param $list Mixed: Correctly formatted text (newline delimited) to be used to generate the options
472 * @param $other Mixed: Text for the "Other reasons" option
473 * @param $selected Mixed: Option which should be pre-selected
474 * @param $class Mixed: CSS classes for the drop-down
475 * @param $tabindex Mixed: Value of the tabindex attribute
478 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = null ) {
481 $options = self
::option( $other, 'other', $selected === 'other' );
483 foreach ( explode( "\n", $list ) as $option) {
484 $value = trim( $option );
485 if ( $value == '' ) {
487 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
488 // A new group is starting ...
489 $value = trim( substr( $value, 1 ) );
490 if( $optgroup ) $options .= self
::closeElement('optgroup');
491 $options .= self
::openElement( 'optgroup', array( 'label' => $value ) );
493 } elseif ( substr( $value, 0, 2) == '**' ) {
495 $value = trim( substr( $value, 2 ) );
496 $options .= self
::option( $value, $value, $selected === $value );
498 // groupless reason list
499 if( $optgroup ) $options .= self
::closeElement('optgroup');
500 $options .= self
::option( $value, $value, $selected === $value );
505 if( $optgroup ) $options .= self
::closeElement('optgroup');
510 $attribs['id'] = $name;
511 $attribs['name'] = $name;
515 $attribs['class'] = $class;
519 $attribs['tabindex'] = $tabindex;
522 return Xml
::openElement( 'select', $attribs )
526 . Xml
::closeElement( 'select' );
530 * Shortcut for creating fieldsets.
532 * @param $legend Legend of the fieldset. If evaluates to false, legend is not added.
533 * @param $content Pre-escaped content for the fieldset. If false, only open fieldset is returned.
534 * @param $attribs array Any attributes to fieldset-element.
538 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
539 $s = Xml
::openElement( 'fieldset', $attribs ) . "\n";
542 $s .= Xml
::element( 'legend', null, $legend ) . "\n";
545 if ( $content !== false ) {
546 $s .= $content . "\n";
547 $s .= Xml
::closeElement( 'fieldset' ) . "\n";
554 * Shortcut for creating textareas.
556 * @param $name string The 'name' for the textarea
557 * @param $content string Content for the textarea
558 * @param $cols int The number of columns for the textarea
559 * @param $rows int The number of rows for the textarea
560 * @param $attribs array Any other attributes for the textarea
564 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
565 return self
::element( 'textarea',
566 array( 'name' => $name,
575 * Returns an escaped string suitable for inclusion in a string literal
576 * for JavaScript source code.
577 * Illegal control characters are assumed not to be present.
579 * @param $string String to escape
582 public static function escapeJsString( $string ) {
583 // See ECMA 262 section 7.8.4 for string literal format
591 # To avoid closing the element or CDATA section
595 # To avoid any complaints about bad entity refs
598 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
599 # Encode certain Unicode formatting chars so affected
600 # versions of Gecko don't misinterpret our strings;
601 # this is a common problem with Farsi text.
602 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
603 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
606 return strtr( $string, $pairs );
610 * Encode a variable of unknown type to JavaScript.
611 * Arrays are converted to JS arrays, objects are converted to JS associative
612 * arrays (objects). So cast your PHP associative arrays to objects before
613 * passing them to here.
619 public static function encodeJsVar( $value ) {
620 if ( is_bool( $value ) ) {
621 $s = $value ?
'true' : 'false';
622 } elseif ( is_null( $value ) ) {
624 } elseif ( is_int( $value ) ||
is_float( $value ) ) {
626 } elseif ( is_array( $value ) && // Make sure it's not associative.
627 array_keys($value) === range( 0, count($value) - 1 ) ||
631 foreach ( $value as $elt ) {
635 $s .= self
::encodeJsVar( $elt );
638 } elseif ( $value instanceof XmlJsCode
) {
640 } elseif ( is_object( $value ) ||
is_array( $value ) ) {
641 // Objects and associative arrays
643 foreach ( (array)$value as $name => $elt ) {
648 $s .= '"' . self
::escapeJsString( $name ) . '":' .
649 self
::encodeJsVar( $elt );
653 $s = '"' . self
::escapeJsString( $value ) . '"';
659 * Create a call to a JavaScript function. The supplied arguments will be
660 * encoded using Xml::encodeJsVar().
662 * @param $name String The name of the function to call, or a JavaScript expression
663 * which evaluates to a function object which is called.
664 * @param $args Array of arguments to pass to the function.
670 public static function encodeJsCall( $name, $args ) {
674 foreach ( $args as $arg ) {
681 $s .= Xml
::encodeJsVar( $arg );
690 * Check if a string is well-formed XML.
691 * Must include the surrounding tag.
693 * @param $text String: string to test.
696 * @todo Error position reporting return
698 public static function isWellFormed( $text ) {
699 $parser = xml_parser_create( "UTF-8" );
701 # case folding violates XML standard, turn it off
702 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
704 if( !xml_parse( $parser, $text, true ) ) {
705 //$err = xml_error_string( xml_get_error_code( $parser ) );
706 //$position = xml_get_current_byte_index( $parser );
707 //$fragment = $this->extractFragment( $html, $position );
708 //$this->mXmlError = "$err at byte $position:\n$fragment";
709 xml_parser_free( $parser );
713 xml_parser_free( $parser );
719 * Check if a string is a well-formed XML fragment.
720 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
721 * and can use HTML named entities.
723 * @param $text String:
726 public static function isWellFormedXmlFragment( $text ) {
728 Sanitizer
::hackDocType() .
733 return Xml
::isWellFormed( $html );
737 * Replace " > and < with their respective HTML entities ( ",
740 * @param $in String: text that might contain HTML tags.
741 * @return string Escaped string
743 public static function escapeTagsOnly( $in ) {
745 array( '"', '>', '<' ),
746 array( '"', '>', '<' ),
751 * Generate a form (without the opening form element).
752 * Output optionally includes a submit button.
753 * @param $fields Array Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
754 * @param $submitLabel String A message containing a label for the submit button.
755 * @return string HTML form.
757 public static function buildForm( $fields, $submitLabel = null ) {
759 $form .= "<table><tbody>";
761 foreach( $fields as $labelmsg => $input ) {
762 $id = "mw-$labelmsg";
763 $form .= Xml
::openElement( 'tr', array( 'id' => $id ) );
764 $form .= Xml
::tags( 'td', array('class' => 'mw-label'), wfMsgExt( $labelmsg, array('parseinline') ) );
765 $form .= Xml
::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml
::closeElement( 'td' );
766 $form .= Xml
::closeElement( 'tr' );
770 $form .= Xml
::openElement( 'tr' );
771 $form .= Xml
::tags( 'td', array(), '' );
772 $form .= Xml
::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml
::submitButton( wfMsg( $submitLabel ) ) . Xml
::closeElement( 'td' );
773 $form .= Xml
::closeElement( 'tr' );
776 $form .= "</tbody></table>";
782 * Build a table of data
783 * @param $rows array An array of arrays of strings, each to be a row in a table
784 * @param $attribs array An array of attributes to apply to the table tag [optional]
785 * @param $headers array An array of strings to use as table headers [optional]
788 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
789 $s = Xml
::openElement( 'table', $attribs );
791 if ( is_array( $headers ) ) {
792 $s .= Xml
::openElement( 'thead', $attribs );
794 foreach( $headers as $id => $header ) {
797 if ( is_string( $id ) ) {
798 $attribs['id'] = $id;
801 $s .= Xml
::element( 'th', $attribs, $header );
803 $s .= Xml
::closeElement( 'thead' );
806 foreach( $rows as $id => $row ) {
809 if ( is_string( $id ) ) {
810 $attribs['id'] = $id;
813 $s .= Xml
::buildTableRow( $attribs, $row );
816 $s .= Xml
::closeElement( 'table' );
822 * Build a row for a table
823 * @param $attribs array An array of attributes to apply to the tr tag
824 * @param $cells array An array of strings to put in <td>
827 public static function buildTableRow( $attribs, $cells ) {
828 $s = Xml
::openElement( 'tr', $attribs );
830 foreach( $cells as $id => $cell ) {
834 if ( is_string( $id ) ) {
835 $attribs['id'] = $id;
838 $s .= Xml
::element( 'td', $attribs, $cell );
841 $s .= Xml
::closeElement( 'tr' );
848 protected $options = array();
849 protected $default = false;
850 protected $attributes = array();
852 public function __construct( $name = false, $id = false, $default = false ) {
854 $this->setAttribute( 'name', $name );
858 $this->setAttribute( 'id', $id );
861 if ( $default !== false ) {
862 $this->default = $default;
869 public function setDefault( $default ) {
870 $this->default = $default;
874 * @param $name string
877 public function setAttribute( $name, $value ) {
878 $this->attributes
[$name] = $value;
885 public function getAttribute( $name ) {
886 if ( isset( $this->attributes
[$name] ) ) {
887 return $this->attributes
[$name];
897 public function addOption( $name, $value = false ) {
899 $value = ($value !== false) ?
$value : $name;
901 $this->options
[] = array( $name => $value );
905 * This accepts an array of form
907 * label => ( label => value, label => value )
911 public function addOptions( $options ) {
912 $this->options
[] = $options;
916 * This accepts an array of form
918 * label => ( label => value, label => value )
921 * @param bool $default
924 static function formatOptions( $options, $default = false ) {
927 foreach( $options as $label => $value ) {
928 if ( is_array( $value ) ) {
929 $contents = self
::formatOptions( $value, $default );
930 $data .= Html
::rawElement( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
932 $data .= Xml
::option( $label, $value, $value === $default ) . "\n";
942 public function getHTML() {
945 foreach ( $this->options
as $options ) {
946 $contents .= self
::formatOptions( $options, $this->default );
949 return Html
::rawElement( 'select', $this->attributes
, rtrim( $contents ) );
954 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
955 * interpret a given string as being a JavaScript expression, instead of string
960 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
968 function __construct( $value ) {
969 $this->value
= $value;