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 private 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 ) . '"';
53 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__
);
58 * Given a string of attributes for an element, return an array of key =>
59 * value pairs. Can be used for backward compatibility with old functions
60 * that accept attributes as strings instead of arrays. Does not validate
61 * the string, so watch out for GIGO.
63 * @param $attribs string
66 public static function explodeAttributes( $attribs ) {
68 preg_match_all( '/([^\s=\'"]+)\s*=\s*(?:\'([^\']*)\'|"([^"]*)")/',
71 for( $i = 0; $i < count( $matches[0] ); ++
$i ) {
72 if( $matches[2][$i] !== '' ) {
73 $val = $matches[2][$i];
75 $val = $matches[3][$i];
77 $ret[$matches[1][$i]] = html_entity_decode( $val );
83 * Format an XML element as with self::element(), but run text through the
84 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
87 * @param $element String:
88 * @param $attribs Array: Name=>value pairs. Values will be escaped.
89 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
92 public static function elementClean( $element, $attribs = array(), $contents = '') {
94 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
97 wfProfileIn( __METHOD__
. '-norm' );
98 $contents = UtfNormal
::cleanUp( $contents );
99 wfProfileOut( __METHOD__
. '-norm' );
101 return self
::element( $element, $attribs, $contents );
105 * This opens an XML element
107 * @param $element name of the element
108 * @param $attribs array of attributes, see Xml::expandAttributes()
111 public static function openElement( $element, $attribs = null ) {
112 return '<' . $element . self
::expandAttributes( $attribs ) . '>';
116 * Shortcut to close an XML element
117 * @param $element element name
120 public static function closeElement( $element ) { return "</$element>"; }
123 * Same as Xml::element(), but does not escape contents. Handy when the
124 * content you have is already valid xml.
126 * @param $element element name
127 * @param $attribs array of attributes
128 * @param $contents content of the element
131 public static function tags( $element, $attribs = null, $contents ) {
132 return self
::openElement( $element, $attribs ) . $contents . "</$element>";
136 * Build a drop-down box for selecting a namespace
138 * @param $selected Mixed: Namespace which should be pre-selected
139 * @param $all Mixed: Value of an item denoting all namespaces, or null to omit
140 * @param $hidden Mixed: Include hidden namespaces? [WTF? --RC]
141 * @param $element_name String: value of the "name" attribute of the select tag
144 public static function namespaceSelector( $selected = '', $all = null, $hidden = false, $element_name = 'namespace' ) {
146 $namespaces = $wgContLang->getFormattedNamespaces();
149 // Godawful hack... we'll be frequently passed selected namespaces
150 // as strings since PHP is such a shithole.
151 // But we also don't want blanks and nulls and "all"s matching 0,
152 // so let's convert *just* string ints to clean ints.
153 if( preg_match( '/^\d+$/', $selected ) ) {
154 $selected = intval( $selected );
157 if( !is_null( $all ) )
158 $namespaces = array( $all => wfMsg( 'namespacesall' ) ) +
$namespaces;
159 foreach( $namespaces as $index => $name ) {
160 if( $index < NS_MAIN
)
163 $name = wfMsg( 'blanknamespace' );
164 $options[] = self
::option( $name, $index, $index === $selected );
167 return Xml
::openElement( 'select', array( 'id' => 'namespace', 'name' => $element_name,
168 'class' => 'namespaceselector' ) )
170 . implode( "\n", $options )
172 . Xml
::closeElement( 'select' );
176 * Create a date selector
178 * @param $selected Mixed: the month which should be selected, default ''
179 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
180 * @param $id String: Element identifier
181 * @return String: Html string containing the month selector
183 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
186 if( is_null( $selected ) )
188 if( !is_null( $allmonths ) )
189 $options[] = self
::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
190 for( $i = 1; $i < 13; $i++
)
191 $options[] = self
::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
192 return self
::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
193 . implode( "\n", $options )
194 . self
::closeElement( 'select' );
199 * @param $selected The language code of the selected language
200 * @param $customisedOnly If true only languages which have some content are listed
201 * @return array of label and select
203 public static function languageSelector( $selected, $customisedOnly = true ) {
204 global $wgContLanguageCode;
206 * Make sure the site language is in the list; a custom language code
207 * might not have a defined name...
209 $languages = Language
::getLanguageNames( $customisedOnly );
210 if( !array_key_exists( $wgContLanguageCode, $languages ) ) {
211 $languages[$wgContLanguageCode] = $wgContLanguageCode;
216 * If a bogus value is set, default to the content language.
217 * Otherwise, no default is selected and the user ends up
218 * with an Afrikaans interface since it's first in the list.
220 $selected = isset( $languages[$selected] ) ?
$selected : $wgContLanguageCode;
222 foreach( $languages as $code => $name ) {
223 $options .= Xml
::option( "$code - $name", $code, ($code == $selected) ) . "\n";
227 Xml
::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
229 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
237 * Shortcut to make a span element
238 * @param $text content of the element, will be escaped
239 * @param $class class name of the span element
240 * @param $attribs other attributes
243 public static function span( $text, $class, $attribs=array() ) {
244 return self
::element( 'span', array( 'class' => $class ) +
$attribs, $text );
248 * Shortcut to make a specific element with a class attribute
249 * @param $text content of the element, will be escaped
250 * @param $class class name of the span element
251 * @param $tag element name
252 * @param $attribs other attributes
255 public static function wrapClass( $text, $class, $tag='span', $attribs=array() ) {
256 return self
::tags( $tag, array( 'class' => $class ) +
$attribs, $text );
260 * Convenience function to build an HTML text input field
261 * @param $name value of the name attribute
262 * @param $size value of the size attribute
263 * @param $value value of the value attribute
264 * @param $attribs other attributes
265 * @return string HTML
267 public static function input( $name, $size=false, $value=false, $attribs=array() ) {
268 return self
::element( 'input', array(
271 'value' => $value ) +
$attribs );
275 * Convenience function to build an HTML password input field
276 * @param $name value of the name attribute
277 * @param $size value of the size attribute
278 * @param $value value of the value attribute
279 * @param $attribs other attributes
280 * @return string HTML
282 public static function password( $name, $size=false, $value=false, $attribs=array() ) {
283 return self
::input( $name, $size, $value, array_merge($attribs, array('type' => 'password')));
287 * Internal function for use in checkboxes and radio buttons and such.
290 public static function attrib( $name, $present = true ) {
291 return $present ?
array( $name => $name ) : array();
295 * Convenience function to build an HTML checkbox
296 * @param $name value of the name attribute
297 * @param $checked Whether the checkbox is checked or not
298 * @param $attribs other attributes
299 * @return string HTML
301 public static function check( $name, $checked=false, $attribs=array() ) {
302 return self
::element( 'input', array_merge(
305 'type' => 'checkbox',
307 self
::attrib( 'checked', $checked ),
312 * Convenience function to build an HTML radio button
313 * @param $name value of the name attribute
314 * @param $value value of the value attribute
315 * @param $checked Whether the checkbox is checked or not
316 * @param $attribs other attributes
317 * @return string HTML
319 public static function radio( $name, $value, $checked=false, $attribs=array() ) {
320 return self
::element( 'input', array(
323 'value' => $value ) + self
::attrib( 'checked', $checked ) +
$attribs );
327 * Convenience function to build an HTML form label
328 * @param $label text of the label
330 * @return string HTML
332 public static function label( $label, $id ) {
333 return self
::element( 'label', array( 'for' => $id ), $label );
337 * Convenience function to build an HTML text input field with a label
338 * @param $label text of the label
339 * @param $name value of the name attribute
340 * @param $id id of the input
341 * @param $size value of the size attribute
342 * @param $value value of the value attribute
343 * @param $attribs other attributes
344 * @return string HTML
346 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
347 list( $label, $input ) = self
::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
348 return $label . ' ' . $input;
352 * Same as Xml::inputLabel() but return input and label in an array
354 public static function inputLabelSep( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
356 Xml
::label( $label, $id ),
357 self
::input( $name, $size, $value, array( 'id' => $id ) +
$attribs )
362 * Convenience function to build an HTML checkbox with a label
363 * @return string HTML
365 public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
366 return self
::check( $name, $checked, array( 'id' => $id ) +
$attribs ) .
368 self
::label( $label, $id );
372 * Convenience function to build an HTML radio button with a label
373 * @return string HTML
375 public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
376 return self
::radio( $name, $value, $checked, array( 'id' => $id ) +
$attribs ) .
378 self
::label( $label, $id );
382 * Convenience function to build an HTML submit button
383 * @param $value String: label text for the button
384 * @param $attribs Array: optional custom attributes
385 * @return string HTML
387 public static function submitButton( $value, $attribs=array() ) {
388 return self
::element( 'input', array( 'type' => 'submit', 'value' => $value ) +
$attribs );
392 * Convenience function to build an HTML hidden form field.
393 * @param $name String: name attribute for the field
394 * @param $value String: value for the hidden field
395 * @param $attribs Array: optional custom attributes
396 * @return string HTML
398 public static function hidden( $name, $value, $attribs=array() ) {
399 return self
::element( 'input', array(
402 'value' => $value ) +
$attribs );
406 * Convenience function to build an HTML drop-down list item.
407 * @param $text String: text for this item
408 * @param $value String: form submission value; if empty, use text
409 * @param $selected boolean: if true, will be the default selected item
410 * @param $attribs array: optional additional HTML attributes
411 * @return string HTML
413 public static function option( $text, $value=null, $selected=false,
415 if( !is_null( $value ) ) {
416 $attribs['value'] = $value;
419 $attribs['selected'] = 'selected';
421 return self
::element( 'option', $attribs, $text );
425 * Build a drop-down box from a textual list.
427 * @param $name Mixed: Name and id for the drop-down
428 * @param $class Mixed: CSS classes for the drop-down
429 * @param $other Mixed: Text for the "Other reasons" option
430 * @param $list Mixed: Correctly formatted text to be used to generate the options
431 * @param $selected Mixed: Option which should be pre-selected
432 * @param $tabindex Mixed: Value of the tabindex attribute
435 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = Null ) {
439 $options = self
::option( $other, 'other', $selected === 'other' );
441 foreach ( explode( "\n", $list ) as $option) {
442 $value = trim( $option );
443 if ( $value == '' ) {
445 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
446 // A new group is starting ...
447 $value = trim( substr( $value, 1 ) );
448 if( $optgroup ) $options .= self
::closeElement('optgroup');
449 $options .= self
::openElement( 'optgroup', array( 'label' => $value ) );
451 } elseif ( substr( $value, 0, 2) == '**' ) {
453 $value = trim( substr( $value, 2 ) );
454 $options .= self
::option( $value, $value, $selected === $value );
456 // groupless reason list
457 if( $optgroup ) $options .= self
::closeElement('optgroup');
458 $options .= self
::option( $value, $value, $selected === $value );
462 if( $optgroup ) $options .= self
::closeElement('optgroup');
466 $attribs['id'] = $name;
467 $attribs['name'] = $name;
470 $attribs['class'] = $class;
473 $attribs['tabindex'] = $tabindex;
475 return Xml
::openElement( 'select', $attribs )
479 . Xml
::closeElement( 'select' );
483 * Shortcut for creating fieldsets.
485 * @param $legend Legend of the fieldset. If evaluates to false, legend is not added.
486 * @param $content Pre-escaped content for the fieldset. If false, only open fieldset is returned.
487 * @param $attribs Any attributes to fieldset-element.
489 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
490 $s = Xml
::openElement( 'fieldset', $attribs ) . "\n";
492 $s .= Xml
::element( 'legend', null, $legend ) . "\n";
494 if ( $content !== false ) {
495 $s .= $content . "\n";
496 $s .= Xml
::closeElement( 'fieldset' ) . "\n";
503 * Shortcut for creating textareas.
505 * @param $name The 'name' for the textarea
506 * @param $content Content for the textarea
507 * @param $cols The number of columns for the textarea
508 * @param $rows The number of rows for the textarea
509 * @param $attribs Any other attributes for the textarea
511 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
512 return self
::element( 'textarea',
513 array( 'name' => $name,
522 * Returns an escaped string suitable for inclusion in a string literal
523 * for JavaScript source code.
524 * Illegal control characters are assumed not to be present.
526 * @param $string String to escape
529 public static function escapeJsString( $string ) {
530 // See ECMA 262 section 7.8.4 for string literal format
538 # To avoid closing the element or CDATA section
542 # To avoid any complaints about bad entity refs
545 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
546 # Encode certain Unicode formatting chars so affected
547 # versions of Gecko don't misinterpret our strings;
548 # this is a common problem with Farsi text.
549 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
550 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
552 return strtr( $string, $pairs );
556 * Encode a variable of unknown type to JavaScript.
557 * Arrays are converted to JS arrays, objects are converted to JS associative
558 * arrays (objects). So cast your PHP associative arrays to objects before
559 * passing them to here.
561 public static function encodeJsVar( $value ) {
562 if ( is_bool( $value ) ) {
563 $s = $value ?
'true' : 'false';
564 } elseif ( is_null( $value ) ) {
566 } elseif ( is_int( $value ) ) {
568 } elseif ( is_array( $value ) ) {
570 foreach ( $value as $elt ) {
574 $s .= self
::encodeJsVar( $elt );
577 } elseif ( is_object( $value ) ) {
579 foreach ( (array)$value as $name => $elt ) {
583 $s .= '"' . self
::escapeJsString( $name ) . '": ' .
584 self
::encodeJsVar( $elt );
588 $s = '"' . self
::escapeJsString( $value ) . '"';
595 * Check if a string is well-formed XML.
596 * Must include the surrounding tag.
598 * @param $text String: string to test.
601 * @todo Error position reporting return
603 public static function isWellFormed( $text ) {
604 $parser = xml_parser_create( "UTF-8" );
606 # case folding violates XML standard, turn it off
607 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING
, false );
609 if( !xml_parse( $parser, $text, true ) ) {
610 //$err = xml_error_string( xml_get_error_code( $parser ) );
611 //$position = xml_get_current_byte_index( $parser );
612 //$fragment = $this->extractFragment( $html, $position );
613 //$this->mXmlError = "$err at byte $position:\n$fragment";
614 xml_parser_free( $parser );
617 xml_parser_free( $parser );
622 * Check if a string is a well-formed XML fragment.
623 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
624 * and can use HTML named entities.
626 * @param $text String:
629 public static function isWellFormedXmlFragment( $text ) {
631 Sanitizer
::hackDocType() .
635 return Xml
::isWellFormed( $html );
639 * Replace " > and < with their respective HTML entities ( ",
642 * @param $in String: text that might contain HTML tags.
643 * @return string Escaped string
645 public static function escapeTagsOnly( $in ) {
647 array( '"', '>', '<' ),
648 array( '"', '>', '<' ),
653 * Generate a form (without the opening form element).
654 * Output optionally includes a submit button.
655 * @param $fields Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
656 * @param $submitLabel A message containing a label for the submit button.
657 * @return string HTML form.
659 public static function buildForm( $fields, $submitLabel = null ) {
661 $form .= "<table><tbody>";
663 foreach( $fields as $labelmsg => $input ) {
664 $id = "mw-$labelmsg";
666 $form .= Xml
::openElement( 'tr', array( 'id' => $id ) );
667 $form .= Xml
::tags( 'td', array('class' => 'mw-label'), wfMsgExt( $labelmsg, array('parseinline') ) );
668 $form .= Xml
::openElement( 'td' ) . $input . Xml
::closeElement( 'td' );
669 $form .= Xml
::closeElement( 'tr' );
672 $form .= "</tbody></table>";
675 $form .= Xml
::submitButton( wfMsg($submitLabel) );
683 protected $options = array();
684 protected $default = false;
685 protected $attributes = array();
687 public function __construct( $name = false, $id = false, $default = false ) {
688 if ( $name ) $this->setAttribute( 'name', $name );
689 if ( $id ) $this->setAttribute( 'id', $id );
690 if ( $default ) $this->default = $default;
693 public function setDefault( $default ) {
694 $this->default = $default;
697 public function setAttribute( $name, $value ) {
698 $this->attributes
[$name] = $value;
701 public function addOption( $name, $value = false ) {
702 $value = $value ?
$value : $name;
703 $this->options
[] = Xml
::option( $name, $value, $value === $this->default );
706 public function getHTML() {
707 return Xml
::tags( 'select', $this->attributes
, implode( "\n", $this->options
) );