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
121 public static function namespaceSelector( $selected = '', $all = null, $element_name = 'namespace', $label = null ) {
123 $namespaces = $wgContLang->getFormattedNamespaces();
126 // Godawful hack... we'll be frequently passed selected namespaces
127 // as strings since PHP is such a shithole.
128 // But we also don't want blanks and nulls and "all"s matching 0,
129 // so let's convert *just* string ints to clean ints.
130 if( preg_match( '/^\d+$/', $selected ) ) {
131 $selected = intval( $selected );
134 if( !is_null( $all ) )
135 $namespaces = array( $all => wfMsg( 'namespacesall' ) ) +
$namespaces;
136 foreach( $namespaces as $index => $name ) {
137 if( $index < NS_MAIN
) {
141 $name = wfMsg( 'blanknamespace' );
143 $options[] = self
::option( $name, $index, $index === $selected );
146 $ret = Xml
::openElement( 'select', array( 'id' => 'namespace', 'name' => $element_name,
147 'class' => 'namespaceselector' ) )
149 . implode( "\n", $options )
151 . Xml
::closeElement( 'select' );
152 if ( !is_null( $label ) ) {
153 $ret = Xml
::label( $label, $element_name ) . ' ' . $ret;
159 * Create a date selector
161 * @param $selected Mixed: the month which should be selected, default ''
162 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
163 * @param $id String: Element identifier
164 * @return String: Html string containing the month selector
166 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
169 if( is_null( $selected ) )
171 if( !is_null( $allmonths ) )
172 $options[] = self
::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
173 for( $i = 1; $i < 13; $i++
)
174 $options[] = self
::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
175 return self
::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
176 . implode( "\n", $options )
177 . self
::closeElement( 'select' );
181 * @param $year Integer
182 * @param $month Integer
183 * @return string Formatted HTML
185 public static function dateMenu( $year, $month ) {
186 # Offset overrides year/month selection
187 if( $month && $month !== -1 ) {
188 $encMonth = intval( $month );
193 $encYear = intval( $year );
194 } else if( $encMonth ) {
195 $thisMonth = intval( gmdate( 'n' ) );
196 $thisYear = intval( gmdate( 'Y' ) );
197 if( intval($encMonth) > $thisMonth ) {
200 $encYear = $thisYear;
204 return Xml
::label( wfMsg( 'year' ), 'year' ) . ' '.
205 Xml
::input( 'year', 4, $encYear, array('id' => 'year', 'maxlength' => 4) ) . ' '.
206 Xml
::label( wfMsg( 'month' ), 'month' ) . ' '.
207 Xml
::monthSelector( $encMonth, -1 );
212 * @param $selected string The language code of the selected language
213 * @param $customisedOnly bool If true only languages which have some content are listed
214 * @return array of label and select
216 public static function languageSelector( $selected, $customisedOnly = true ) {
217 global $wgLanguageCode;
219 * Make sure the site language is in the list; a custom language code
220 * might not have a defined name...
222 $languages = Language
::getLanguageNames( $customisedOnly );
223 if( !array_key_exists( $wgLanguageCode, $languages ) ) {
224 $languages[$wgLanguageCode] = $wgLanguageCode;
229 * If a bogus value is set, default to the content language.
230 * Otherwise, no default is selected and the user ends up
231 * with an Afrikaans interface since it's first in the list.
233 $selected = isset( $languages[$selected] ) ?
$selected : $wgLanguageCode;
235 foreach( $languages as $code => $name ) {
236 $options .= Xml
::option( "$code - $name", $code, ($code == $selected) ) . "\n";
240 Xml
::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
242 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
250 * Shortcut to make a span element
251 * @param $text String content of the element, will be escaped
252 * @param $class String class name of the span element
253 * @param $attribs array other attributes
256 public static function span( $text, $class, $attribs = array() ) {
257 return self
::element( 'span', array( 'class' => $class ) +
$attribs, $text );
261 * Shortcut to make a specific element with a class attribute
262 * @param $text content of the element, will be escaped
263 * @param $class class name of the span element
264 * @param $tag string element name
265 * @param $attribs array other attributes
268 public static function wrapClass( $text, $class, $tag = 'span', $attribs = array() ) {
269 return self
::tags( $tag, array( 'class' => $class ) +
$attribs, $text );
273 * Convenience function to build an HTML text input field
274 * @param $name String value of the name attribute
275 * @param $size int value of the size attribute
276 * @param $value mixed value of the value attribute
277 * @param $attribs array other attributes
278 * @return string HTML
280 public static function input( $name, $size = false, $value = false, $attribs = array() ) {
281 $attributes = array( 'name' => $name );
284 $attributes['size'] = $size;
287 if( $value !== false ) { // maybe 0
288 $attributes['value'] = $value;
291 return self
::element( 'input', $attributes +
$attribs );
295 * Convenience function to build an HTML password input field
296 * @param $name string value of the name attribute
297 * @param $size int value of the size attribute
298 * @param $value mixed value of the value attribute
299 * @param $attribs array other attributes
300 * @return string HTML
302 public static function password( $name, $size = false, $value = false, $attribs = array() ) {
303 return self
::input( $name, $size, $value, array_merge( $attribs, array( 'type' => 'password' ) ) );
307 * Internal function for use in checkboxes and radio buttons and such.
309 * @param $name string
310 * @param $present bool
314 public static function attrib( $name, $present = true ) {
315 return $present ?
array( $name => $name ) : array();
319 * Convenience function to build an HTML checkbox
320 * @param $name String value of the name attribute
321 * @param $checked Bool Whether the checkbox is checked or not
322 * @param $attribs Array other attributes
323 * @return string HTML
325 public static function check( $name, $checked = false, $attribs=array() ) {
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 $name value of the name attribute
338 * @param $value value of the value attribute
339 * @param $checked Whether the checkbox is checked or not
340 * @param $attribs other attributes
341 * @return string HTML
343 public static function radio( $name, $value, $checked = false, $attribs = array() ) {
344 return self
::element( 'input', array(
347 'value' => $value ) + self
::attrib( 'checked', $checked ) +
$attribs );
351 * Convenience function to build an HTML form label
352 * @param $label String text of the label
354 * @param $attribs Array an attribute array. This will usuall 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; currently only class is applied.
358 * @return string HTML
360 public static function label( $label, $id, $attribs = array() ) {
361 $a = array( 'for' => $id );
362 if( isset( $attribs['class'] ) ){
363 $a['class'] = $attribs['class'];
365 return self
::element( 'label', $a, $label );
369 * Convenience function to build an HTML text input field with a label
370 * @param $label String text of the label
371 * @param $name String value of the name attribute
372 * @param $id String id of the input
373 * @param $size int value of the size attribute
374 * @param $value value of the value attribute
375 * @param $attribs array other attributes
376 * @return string HTML
378 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs = array() ) {
379 list( $label, $input ) = self
::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
380 return $label . ' ' . $input;
384 * Same as Xml::inputLabel() but return input and label in an array
391 * @param $attribs array
395 public static function inputLabelSep( $label, $name, $id, $size = false, $value = false, $attribs = array() ) {
397 Xml
::label( $label, $id, $attribs ),
398 self
::input( $name, $size, $value, array( 'id' => $id ) +
$attribs )
403 * Convenience function to build an HTML checkbox with a label
408 * @param $checked bool
409 * @param $attribs array
411 * @return string HTML
413 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = array() ) {
414 return self
::check( $name, $checked, array( 'id' => $id ) +
$attribs ) .
416 self
::label( $label, $id, $attribs );
420 * Convenience function to build an HTML radio button with a label
426 * @param $checked bool
427 * @param $attribs array
429 * @return string HTML
431 public static function radioLabel( $label, $name, $value, $id, $checked = false, $attribs = array() ) {
432 return self
::radio( $name, $value, $checked, array( 'id' => $id ) +
$attribs ) .
434 self
::label( $label, $id, $attribs );
438 * Convenience function to build an HTML submit button
439 * @param $value String: label text for the button
440 * @param $attribs Array: optional custom attributes
441 * @return string HTML
443 public static function submitButton( $value, $attribs = array() ) {
444 return Html
::element( 'input', array( 'type' => 'submit', 'value' => $value ) +
$attribs );
448 * Convenience function to build an HTML drop-down list item.
449 * @param $text String: text for this item
450 * @param $value String: form submission value; if empty, use text
451 * @param $selected boolean: if true, will be the default selected item
452 * @param $attribs array: optional additional HTML attributes
453 * @return string HTML
455 public static function option( $text, $value=null, $selected = false,
456 $attribs = array() ) {
457 if( !is_null( $value ) ) {
458 $attribs['value'] = $value;
461 $attribs['selected'] = 'selected';
463 return self
::element( 'option', $attribs, $text );
467 * Build a drop-down box from a textual list.
469 * @param $name Mixed: Name and id for the drop-down
470 * @param $list Mixed: Correctly formatted text (newline delimited) to be used to generate the options
471 * @param $other Mixed: Text for the "Other reasons" option
472 * @param $selected Mixed: Option which should be pre-selected
473 * @param $class Mixed: CSS classes for the drop-down
474 * @param $tabindex Mixed: Value of the tabindex attribute
477 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = null ) {
480 $options = self
::option( $other, 'other', $selected === 'other' );
482 foreach ( explode( "\n", $list ) as $option) {
483 $value = trim( $option );
484 if ( $value == '' ) {
486 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
487 // A new group is starting ...
488 $value = trim( substr( $value, 1 ) );
489 if( $optgroup ) $options .= self
::closeElement('optgroup');
490 $options .= self
::openElement( 'optgroup', array( 'label' => $value ) );
492 } elseif ( substr( $value, 0, 2) == '**' ) {
494 $value = trim( substr( $value, 2 ) );
495 $options .= self
::option( $value, $value, $selected === $value );
497 // groupless reason list
498 if( $optgroup ) $options .= self
::closeElement('optgroup');
499 $options .= self
::option( $value, $value, $selected === $value );
503 if( $optgroup ) $options .= self
::closeElement('optgroup');
507 $attribs['id'] = $name;
508 $attribs['name'] = $name;
511 $attribs['class'] = $class;
514 $attribs['tabindex'] = $tabindex;
516 return Xml
::openElement( 'select', $attribs )
520 . Xml
::closeElement( 'select' );
524 * Shortcut for creating fieldsets.
526 * @param $legend Legend of the fieldset. If evaluates to false, legend is not added.
527 * @param $content Pre-escaped content for the fieldset. If false, only open fieldset is returned.
528 * @param $attribs array Any attributes to fieldset-element.
532 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
533 $s = Xml
::openElement( 'fieldset', $attribs ) . "\n";
535 $s .= Xml
::element( 'legend', null, $legend ) . "\n";
537 if ( $content !== false ) {
538 $s .= $content . "\n";
539 $s .= Xml
::closeElement( 'fieldset' ) . "\n";
546 * Shortcut for creating textareas.
548 * @param $name string The 'name' for the textarea
549 * @param $content string Content for the textarea
550 * @param $cols int The number of columns for the textarea
551 * @param $rows int The number of rows for the textarea
552 * @param $attribs array Any other attributes for the textarea
556 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
557 return self
::element( 'textarea',
558 array( 'name' => $name,
567 * Returns an escaped string suitable for inclusion in a string literal
568 * for JavaScript source code.
569 * Illegal control characters are assumed not to be present.
571 * @param $string String to escape
574 public static function escapeJsString( $string ) {
575 // See ECMA 262 section 7.8.4 for string literal format
583 # To avoid closing the element or CDATA section
587 # To avoid any complaints about bad entity refs
590 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
591 # Encode certain Unicode formatting chars so affected
592 # versions of Gecko don't misinterpret our strings;
593 # this is a common problem with Farsi text.
594 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
595 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
597 return strtr( $string, $pairs );
601 * Encode a variable of unknown type to JavaScript.
602 * Arrays are converted to JS arrays, objects are converted to JS associative
603 * arrays (objects). So cast your PHP associative arrays to objects before
604 * passing them to here.
610 public static function encodeJsVar( $value ) {
611 if ( is_bool( $value ) ) {
612 $s = $value ?
'true' : 'false';
613 } elseif ( is_null( $value ) ) {
615 } elseif ( is_int( $value ) ||
is_float( $value ) ) {
617 } elseif ( is_array( $value ) && // Make sure it's not associative.
618 array_keys($value) === range( 0, count($value) - 1 ) ||
622 foreach ( $value as $elt ) {
626 $s .= self
::encodeJsVar( $elt );
629 } elseif ( $value instanceof XmlJsCode
) {
631 } elseif ( is_object( $value ) ||
is_array( $value ) ) {
632 // Objects and associative arrays
634 foreach ( (array)$value as $name => $elt ) {
638 $s .= '"' . self
::escapeJsString( $name ) . '": ' .
639 self
::encodeJsVar( $elt );
643 $s = '"' . self
::escapeJsString( $value ) . '"';
649 * Create a call to a JavaScript function. The supplied arguments will be
650 * encoded using Xml::encodeJsVar().
652 * @param $name String The name of the function to call, or a JavaScript expression
653 * which evaluates to a function object which is called.
654 * @param $args Array of arguments to pass to the function.
660 public static function encodeJsCall( $name, $args ) {
663 foreach ( $args as $arg ) {
669 $s .= Xml
::encodeJsVar( $arg );
677 * Check if a string is well-formed XML.
678 * Must include the surrounding tag.
680 * @param $text String: string to test.
683 * @todo Error position reporting return
685 public static function isWellFormed( $text ) {
686 $parser = xml_parser_create( "UTF-8" );
688 # case folding violates XML standard, turn it off
689 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
691 if( !xml_parse( $parser, $text, true ) ) {
692 //$err = xml_error_string( xml_get_error_code( $parser ) );
693 //$position = xml_get_current_byte_index( $parser );
694 //$fragment = $this->extractFragment( $html, $position );
695 //$this->mXmlError = "$err at byte $position:\n$fragment";
696 xml_parser_free( $parser );
699 xml_parser_free( $parser );
704 * Check if a string is a well-formed XML fragment.
705 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
706 * and can use HTML named entities.
708 * @param $text String:
711 public static function isWellFormedXmlFragment( $text ) {
713 Sanitizer
::hackDocType() .
717 return Xml
::isWellFormed( $html );
721 * Replace " > and < with their respective HTML entities ( ",
724 * @param $in String: text that might contain HTML tags.
725 * @return string Escaped string
727 public static function escapeTagsOnly( $in ) {
729 array( '"', '>', '<' ),
730 array( '"', '>', '<' ),
735 * Generate a form (without the opening form element).
736 * Output optionally includes a submit button.
737 * @param $fields Array Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
738 * @param $submitLabel String A message containing a label for the submit button.
739 * @return string HTML form.
741 public static function buildForm( $fields, $submitLabel = null ) {
743 $form .= "<table><tbody>";
745 foreach( $fields as $labelmsg => $input ) {
746 $id = "mw-$labelmsg";
747 $form .= Xml
::openElement( 'tr', array( 'id' => $id ) );
748 $form .= Xml
::tags( 'td', array('class' => 'mw-label'), wfMsgExt( $labelmsg, array('parseinline') ) );
749 $form .= Xml
::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml
::closeElement( 'td' );
750 $form .= Xml
::closeElement( 'tr' );
754 $form .= Xml
::openElement( 'tr' );
755 $form .= Xml
::tags( 'td', array(), '' );
756 $form .= Xml
::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml
::submitButton( wfMsg( $submitLabel ) ) . Xml
::closeElement( 'td' );
757 $form .= Xml
::closeElement( 'tr' );
760 $form .= "</tbody></table>";
767 * Build a table of data
768 * @param $rows array An array of arrays of strings, each to be a row in a table
769 * @param $attribs array An array of attributes to apply to the table tag [optional]
770 * @param $headers array An array of strings to use as table headers [optional]
773 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
774 $s = Xml
::openElement( 'table', $attribs );
775 if ( is_array( $headers ) ) {
776 foreach( $headers as $id => $header ) {
778 if ( is_string( $id ) ) $attribs['id'] = $id;
779 $s .= Xml
::element( 'th', $attribs, $header );
782 foreach( $rows as $id => $row ) {
784 if ( is_string( $id ) ) $attribs['id'] = $id;
785 $s .= Xml
::buildTableRow( $attribs, $row );
787 $s .= Xml
::closeElement( 'table' );
792 * Build a row for a table
793 * @param $attribs An array of attributes to apply to the tr tag
794 * @param $cells An array of strings to put in <td>
797 public static function buildTableRow( $attribs, $cells ) {
798 $s = Xml
::openElement( 'tr', $attribs );
799 foreach( $cells as $id => $cell ) {
801 if ( is_string( $id ) ) $attribs['id'] = $id;
802 $s .= Xml
::element( 'td', $attribs, $cell );
804 $s .= Xml
::closeElement( 'tr' );
810 protected $options = array();
811 protected $default = false;
812 protected $attributes = array();
814 public function __construct( $name = false, $id = false, $default = false ) {
816 $this->setAttribute( 'name', $name );
819 $this->setAttribute( 'id', $id );
821 if ( $default !== false ) {
822 $this->default = $default;
829 public function setDefault( $default ) {
830 $this->default = $default;
834 * @param $name string
837 public function setAttribute( $name, $value ) {
838 $this->attributes
[$name] = $value;
845 public function getAttribute( $name ) {
846 if ( isset($this->attributes
[$name]) ) {
847 return $this->attributes
[$name];
857 public function addOption( $name, $value = false ) {
859 $value = ($value !== false) ?
$value : $name;
860 $this->options
[] = Xml
::option( $name, $value, $value === $this->default );
864 * This accepts an array of form
866 * label => ( label => value, label => value )
870 public function addOptions( $options ) {
871 $this->options
[] = trim( self
::formatOptions( $options, $this->default ) );
875 * This accepts an array of form
877 * label => ( label => value, label => value )
880 * @param bool $default
883 static function formatOptions( $options, $default = false ) {
885 foreach( $options as $label => $value ) {
886 if ( is_array( $value ) ) {
887 $contents = self
::formatOptions( $value, $default );
888 $data .= Xml
::tags( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
890 $data .= Xml
::option( $label, $value, $value === $default ) . "\n";
900 public function getHTML() {
901 return Xml
::tags( 'select', $this->attributes
, implode( "\n", $this->options
) );
907 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
908 * interpret a given string as being a JavaScript expression, instead of string
913 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
921 function __construct( $value ) {
922 $this->value
= $value;