MediaWiki master
Xml.php
Go to the documentation of this file.
1<?php
29
33class Xml {
50 public static function element( $element, $attribs = null, $contents = '',
51 $allowShortTag = true
52 ) {
53 $out = '<' . $element;
54 if ( $attribs !== null ) {
55 $out .= self::expandAttributes( $attribs );
56 }
57 if ( $contents === null ) {
58 $out .= '>';
59 } elseif ( $allowShortTag && $contents === '' ) {
60 $out .= ' />';
61 } else {
62 $out .= '>' . htmlspecialchars( $contents, ENT_NOQUOTES ) . "</$element>";
63 }
64 return $out;
65 }
66
75 public static function expandAttributes( ?array $attribs ) {
76 if ( $attribs === null ) {
77 return null;
78 }
79 $out = '';
80 foreach ( $attribs as $name => $val ) {
81 $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
82 }
83 return $out;
84 }
85
97 public static function elementClean( $element, $attribs = [], $contents = '' ) {
98 if ( $attribs ) {
99 $attribs = array_map( [ UtfNormal\Validator::class, 'cleanUp' ], $attribs );
100 }
101 if ( $contents ) {
102 $contents =
103 MediaWikiServices::getInstance()->getContentLanguage()->normalize( $contents );
104 }
105 return self::element( $element, $attribs, $contents );
106 }
107
115 public static function openElement( $element, $attribs = null ) {
116 return '<' . $element . self::expandAttributes( $attribs ) . '>';
117 }
118
124 public static function closeElement( $element ) {
125 return "</$element>";
126 }
127
141 public static function tags( $element, $attribs, $contents ) {
142 return self::openElement( $element, $attribs ) . $contents . "</$element>";
143 }
144
154 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
155 global $wgLang;
156 $options = [];
157
158 $data = new XmlSelect( 'month', $id, $selected ?? '' );
159
160 if ( $allmonths !== null ) {
161 $options[wfMessage( 'monthsall' )->text()] = $allmonths;
162 }
163 for ( $i = 1; $i < 13; $i++ ) {
164 $options[$wgLang->getMonthName( $i )] = $i;
165 }
166 $data->addOptions( $options );
167 $data->setAttribute( 'class', 'mw-month-selector' );
168 return $data->getHTML();
169 }
170
177 public static function dateMenu( $year, $month ) {
178 # Offset overrides year/month selection
179 if ( $month && $month !== -1 ) {
180 $encMonth = intval( $month );
181 } else {
182 $encMonth = '';
183 }
184 if ( $year ) {
185 $encYear = intval( $year );
186 } elseif ( $encMonth ) {
187 $timestamp = MWTimestamp::getInstance();
188 $thisMonth = intval( $timestamp->format( 'n' ) );
189 $thisYear = intval( $timestamp->format( 'Y' ) );
190 if ( $encMonth > $thisMonth ) {
191 $thisYear--;
192 }
193 $encYear = $thisYear;
194 } else {
195 $encYear = '';
196 }
197 $inputAttribs = [ 'id' => 'year', 'maxlength' => 4, 'size' => 7 ];
198 return self::label( wfMessage( 'year' )->text(), 'year' ) . ' ' .
199 Html::input( 'year', $encYear, 'number', $inputAttribs ) . ' ' .
200 self::label( wfMessage( 'month' )->text(), 'month' ) . ' ' .
201 self::monthSelector( $encMonth, '-1' );
202 }
203
214 public static function languageSelector( $selected, $customisedOnly = true,
215 $inLanguage = null, $overrideAttrs = [], Message $msg = null
216 ) {
217 $languageCode = MediaWikiServices::getInstance()->getMainConfig()
218 ->get( MainConfigNames::LanguageCode );
219
220 $include = $customisedOnly ? LanguageNameUtils::SUPPORTED : LanguageNameUtils::DEFINED;
221 $languages = MediaWikiServices::getInstance()
222 ->getLanguageNameUtils()
223 ->getLanguageNames( $inLanguage, $include );
224
225 // Make sure the site language is in the list;
226 // a custom language code might not have a defined name...
227 if ( !array_key_exists( $languageCode, $languages ) ) {
228 $languages[$languageCode] = $languageCode;
229 // Sort the array again
230 ksort( $languages );
231 }
232
238 $selected = isset( $languages[$selected] ) ? $selected : $languageCode;
239 $options = "\n";
240 foreach ( $languages as $code => $name ) {
241 $options .= self::option( "$code - $name", $code, $code == $selected ) . "\n";
242 }
243
244 $attrs = [ 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ];
245 $attrs = array_merge( $attrs, $overrideAttrs );
246
247 if ( $msg === null ) {
248 $msg = wfMessage( 'yourlanguage' );
249 }
250 return [
251 self::label( $msg->text(), $attrs['id'] ),
252 self::tags( 'select', $attrs, $options )
253 ];
254 }
255
264 public static function span( $text, $class, $attribs = [] ) {
265 return self::element( 'span', [ 'class' => $class ] + $attribs, $text );
266 }
267
278 public static function wrapClass( $text, $class, $tag = 'span', $attribs = [] ) {
279 wfDeprecated( __METHOD__, '1.42' );
280 return self::tags( $tag, [ 'class' => $class ] + $attribs, $text );
281 }
282
292 public static function input( $name, $size = false, $value = false, $attribs = [] ) {
293 $attributes = [ 'name' => $name ];
294
295 if ( $size ) {
296 $attributes['size'] = $size;
297 }
298
299 if ( $value !== false ) { // maybe 0
300 $attributes['value'] = $value;
301 }
302
303 return self::element( 'input', $attributes + $attribs );
304 }
305
315 public static function password( $name, $size = false, $value = false,
316 $attribs = []
317 ) {
318 return self::input( $name, $size, $value,
319 array_merge( $attribs, [ 'type' => 'password' ] ) );
320 }
321
330 public static function attrib( $name, $present = true ) {
331 return $present ? [ $name => $name ] : [];
332 }
333
342 public static function check( $name, $checked = false, $attribs = [] ) {
343 return self::element( 'input', array_merge(
344 [
345 'name' => $name,
346 'type' => 'checkbox',
347 'value' => 1 ],
348 self::attrib( 'checked', $checked ),
349 $attribs ) );
350 }
351
361 public static function radio( $name, $value, $checked = false, $attribs = [] ) {
362 return self::element( 'input', [
363 'name' => $name,
364 'type' => 'radio',
365 'value' => $value ] + self::attrib( 'checked', $checked ) + $attribs );
366 }
367
379 public static function label( $label, $id, $attribs = [] ) {
380 $a = [ 'for' => $id ];
381
382 foreach ( [ 'class', 'title' ] as $attr ) {
383 if ( isset( $attribs[$attr] ) ) {
384 $a[$attr] = $attribs[$attr];
385 }
386 }
387
388 return self::element( 'label', $a, $label );
389 }
390
402 public static function inputLabel( $label, $name, $id, $size = false,
403 $value = false, $attribs = []
404 ) {
405 [ $label, $input ] = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
406 return $label . "\u{00A0}" . $input;
407 }
408
422 public static function inputLabelSep( $label, $name, $id, $size = false,
423 $value = false, $attribs = []
424 ) {
425 return [
426 self::label( $label, $id, $attribs ),
427 self::input( $name, $size, $value, [ 'id' => $id ] + $attribs )
428 ];
429 }
430
443 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = [] ) {
444 return self::check( $name, $checked, [ 'id' => $id ] + $attribs ) .
445 "\u{00A0}" .
446 self::label( $label, $id, $attribs );
447 }
448
462 public static function radioLabel( $label, $name, $value, $id,
463 $checked = false, $attribs = []
464 ) {
465 return self::radio( $name, $value, $checked, [ 'id' => $id ] + $attribs ) .
466 "\u{00A0}" .
467 self::label( $label, $id, $attribs );
468 }
469
478 public static function submitButton( $value, $attribs = [] ) {
479 $attribs += [
480 'type' => 'submit',
481 'value' => $value,
482 ];
483 return Html::element( 'input', $attribs );
484 }
485
495 public static function option( $text, $value = null, $selected = false,
496 $attribs = [] ) {
497 if ( $value !== null ) {
498 $attribs['value'] = $value;
499 }
500 if ( $selected ) {
501 $attribs['selected'] = 'selected';
502 }
503 return Html::element( 'option', $attribs, $text );
504 }
505
519 public static function listDropdown( $name = '', $list = '', $other = '',
520 $selected = '', $class = '', $tabindex = null
521 ) {
522 $options = self::listDropdownOptions( $list, [ 'other' => $other ] );
523
524 $xmlSelect = new XmlSelect( $name, $name, $selected );
525 $xmlSelect->addOptions( $options );
526
527 if ( $class ) {
528 $xmlSelect->setAttribute( 'class', $class );
529 }
530 if ( $tabindex ) {
531 $xmlSelect->setAttribute( 'tabindex', $tabindex );
532 }
533
534 return $xmlSelect->getHTML();
535 }
536
550 public static function listDropdownOptions( $list, $params = [] ) {
551 $options = [];
552
553 if ( isset( $params['other'] ) ) {
554 $options[ $params['other'] ] = 'other';
555 }
556
557 $optgroup = false;
558 foreach ( explode( "\n", $list ) as $option ) {
559 $value = trim( $option );
560 if ( $value == '' ) {
561 continue;
562 }
563 if ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
564 # A new group is starting...
565 $value = trim( substr( $value, 1 ) );
566 if ( $value !== '' &&
567 // Do not use the value for 'other' as option group - T251351
568 ( !isset( $params['other'] ) || $value !== $params['other'] )
569 ) {
570 $optgroup = $value;
571 } else {
572 $optgroup = false;
573 }
574 } elseif ( substr( $value, 0, 2 ) == '**' ) {
575 # groupmember
576 $opt = trim( substr( $value, 2 ) );
577 if ( $optgroup === false ) {
578 $options[$opt] = $opt;
579 } else {
580 $options[$optgroup][$opt] = $opt;
581 }
582 } else {
583 # groupless reason list
584 $optgroup = false;
585 $options[$option] = $option;
586 }
587 }
588
589 return $options;
590 }
591
600 public static function listDropdownOptionsOoui( $options ) {
601 $optionsOoui = [];
602
603 foreach ( $options as $text => $value ) {
604 if ( is_array( $value ) ) {
605 $optionsOoui[] = [ 'optgroup' => (string)$text ];
606 foreach ( $value as $text2 => $value2 ) {
607 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
608 }
609 } else {
610 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
611 }
612 }
613
614 return $optionsOoui;
615 }
616
629 public static function fieldset( $legend = false, $content = false, $attribs = [] ) {
630 $s = self::openElement( 'fieldset', $attribs ) . "\n";
631
632 if ( $legend ) {
633 $s .= self::element( 'legend', null, $legend ) . "\n";
634 }
635
636 if ( $content !== false ) {
637 $s .= $content . "\n";
638 $s .= self::closeElement( 'fieldset' ) . "\n";
639 }
640
641 return $s;
642 }
643
656 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = [] ) {
657 return self::element( 'textarea',
658 [
659 'name' => $name,
660 'id' => $name,
661 'cols' => $cols,
662 'rows' => $rows
663 ] + $attribs,
664 $content, false );
665 }
666
681 public static function encodeJsVar( $value, $pretty = false ) {
682 return Html::encodeJsVar( $value, $pretty );
683 }
684
700 public static function encodeJsCall( $name, $args, $pretty = false ) {
701 return Html::encodeJsCall( $name, $args, $pretty );
702 }
703
715 private static function isWellFormed( $text ) {
716 $parser = xml_parser_create( "UTF-8" );
717
718 # case folding violates XML standard, turn it off
719 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
720
721 if ( !xml_parse( $parser, $text, true ) ) {
722 // $err = xml_error_string( xml_get_error_code( $parser ) );
723 // $position = xml_get_current_byte_index( $parser );
724 // $fragment = $this->extractFragment( $html, $position );
725 // $this->mXmlError = "$err at byte $position:\n$fragment";
726 xml_parser_free( $parser );
727 return false;
728 }
729
730 xml_parser_free( $parser );
731
732 return true;
733 }
734
743 public static function isWellFormedXmlFragment( $text ) {
744 $html =
745 Sanitizer::hackDocType() .
746 '<html>' .
747 $text .
748 '</html>';
749
750 return self::isWellFormed( $html );
751 }
752
760 public static function escapeTagsOnly( $in ) {
761 return str_replace(
762 [ '"', '>', '<' ],
763 [ '&quot;', '&gt;', '&lt;' ],
764 $in );
765 }
766
779 public static function buildForm( $fields, $submitLabel = null, $submitAttribs = [] ) {
780 $form = '';
781 $form .= "<table><tbody>";
782
783 foreach ( $fields as $labelmsg => $input ) {
784 $id = "mw-$labelmsg";
785 $form .= self::openElement( 'tr', [ 'id' => $id ] );
786
787 // TODO use a <label> here for accessibility purposes - will need
788 // to either not use a table to build the form, or find the ID of
789 // the input somehow.
790
791 $form .= self::tags( 'td', [ 'class' => 'mw-label' ], wfMessage( $labelmsg )->parse() );
792 $form .= self::openElement( 'td', [ 'class' => 'mw-input' ] )
793 . $input . self::closeElement( 'td' );
794 $form .= self::closeElement( 'tr' );
795 }
796
797 if ( $submitLabel ) {
798 $form .= self::openElement( 'tr' );
799 $form .= self::tags( 'td', [], '' );
800 $form .= self::openElement( 'td', [ 'class' => 'mw-submit' ] )
801 . self::submitButton( wfMessage( $submitLabel )->text(), $submitAttribs )
802 . self::closeElement( 'td' );
803 $form .= self::closeElement( 'tr' );
804 }
805
806 $form .= "</tbody></table>";
807
808 return $form;
809 }
810
817 public static function buildTable( $rows, $attribs = [], $headers = null ) {
818 $s = self::openElement( 'table', $attribs );
819
820 if ( is_array( $headers ) ) {
821 $s .= self::openElement( 'thead', $attribs );
822
823 foreach ( $headers as $id => $header ) {
824 $attribs = [];
825
826 if ( is_string( $id ) ) {
827 $attribs['id'] = $id;
828 }
829
830 $s .= self::element( 'th', $attribs, $header );
831 }
832 $s .= self::closeElement( 'thead' );
833 }
834
835 foreach ( $rows as $id => $row ) {
836 $attribs = [];
837
838 if ( is_string( $id ) ) {
839 $attribs['id'] = $id;
840 }
841
842 $s .= self::buildTableRow( $attribs, $row );
843 }
844
845 $s .= self::closeElement( 'table' );
846
847 return $s;
848 }
849
856 public static function buildTableRow( $attribs, $cells ) {
857 $s = self::openElement( 'tr', $attribs );
858
859 foreach ( $cells as $id => $cell ) {
860 $attribs = [];
861
862 if ( is_string( $id ) ) {
863 $attribs['id'] = $id;
864 }
865
866 $s .= self::element( 'td', $attribs, $cell );
867 }
868
869 $s .= self::closeElement( 'tr' );
870
871 return $s;
872 }
873}
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli') $wgLang
Definition Setup.php:536
array $params
The job parameters.
This class is a collection of static functions that serve two purposes:
Definition Html.php:56
A service that provides utilities to do with language names and codes.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
HTML sanitizer for MediaWiki.
Definition Sanitizer.php:46
Library for creating and parsing MW-style timestamps.
Class for generating HTML <select> or <datalist> elements.
Definition XmlSelect.php:28
Module of static functions for generating XML.
Definition Xml.php:33
static password( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML password input field.
Definition Xml.php:315
static closeElement( $element)
Shortcut to close an XML element.
Definition Xml.php:124
static textarea( $name, $content, $cols=40, $rows=5, $attribs=[])
Shortcut for creating textareas.
Definition Xml.php:656
static inputLabelSep( $label, $name, $id, $size=false, $value=false, $attribs=[])
Same as Xml::inputLabel() but return input and label in an array.
Definition Xml.php:422
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition Xml.php:681
static isWellFormedXmlFragment( $text)
Check if a string is a well-formed XML fragment.
Definition Xml.php:743
static check( $name, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox.
Definition Xml.php:342
static dateMenu( $year, $month)
Definition Xml.php:177
static buildForm( $fields, $submitLabel=null, $submitAttribs=[])
Generate a form (without the opening form element).
Definition Xml.php:779
static listDropdownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Xml.php:600
static listDropdown( $name='', $list='', $other='', $selected='', $class='', $tabindex=null)
Build a drop-down box from a textual list.
Definition Xml.php:519
static attrib( $name, $present=true)
Internal function for use in checkboxes and radio buttons and such.
Definition Xml.php:330
static label( $label, $id, $attribs=[])
Convenience function to build an HTML form label.
Definition Xml.php:379
static openElement( $element, $attribs=null)
This opens an XML element.
Definition Xml.php:115
static input( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field.
Definition Xml.php:292
static wrapClass( $text, $class, $tag='span', $attribs=[])
Shortcut to make a specific element with a class attribute.
Definition Xml.php:278
static buildTable( $rows, $attribs=[], $headers=null)
Definition Xml.php:817
static listDropdownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition Xml.php:550
static submitButton( $value, $attribs=[])
Convenience function to build an HTML submit button.
Definition Xml.php:478
static option( $text, $value=null, $selected=false, $attribs=[])
Convenience function to build an HTML drop-down list item.
Definition Xml.php:495
static checkLabel( $label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition Xml.php:443
static inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field with a label.
Definition Xml.php:402
static languageSelector( $selected, $customisedOnly=true, $inLanguage=null, $overrideAttrs=[], Message $msg=null)
Construct a language selector appropriate for use in a form or preferences.
Definition Xml.php:214
static span( $text, $class, $attribs=[])
Shortcut to make a span element.
Definition Xml.php:264
static escapeTagsOnly( $in)
Replace " > and < with their respective HTML entities ( ", >, <)
Definition Xml.php:760
static tags( $element, $attribs, $contents)
Same as Xml::element(), but does not escape contents.
Definition Xml.php:141
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition Xml.php:50
static radio( $name, $value, $checked=false, $attribs=[])
Convenience function to build an HTML radio button.
Definition Xml.php:361
static buildTableRow( $attribs, $cells)
Build a row for a table.
Definition Xml.php:856
static radioLabel( $label, $name, $value, $id, $checked=false, $attribs=[])
Convenience function to build an HTML radio button with a label.
Definition Xml.php:462
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition Xml.php:700
static expandAttributes(?array $attribs)
Given an array of ('attributename' => 'value'), it generates the code to set the XML attributes : att...
Definition Xml.php:75
static monthSelector( $selected='', $allmonths=null, $id='month')
Create a date selector.
Definition Xml.php:154
static fieldset( $legend=false, $content=false, $attribs=[])
Shortcut for creating fieldsets.
Definition Xml.php:629
static elementClean( $element, $attribs=[], $contents='')
Format an XML element as with self::element(), but run text through the content language's normalize(...
Definition Xml.php:97
$header