MediaWiki 1.40.4
Xml.php
Go to the documentation of this file.
1<?php
27
31class Xml {
44 public static function element( $element, $attribs = null, $contents = '',
45 $allowShortTag = true
46 ) {
47 $out = '<' . $element;
48 if ( $attribs !== null ) {
49 $out .= self::expandAttributes( $attribs );
50 }
51 if ( $contents === null ) {
52 $out .= '>';
53 } elseif ( $allowShortTag && $contents === '' ) {
54 $out .= ' />';
55 } else {
56 $out .= '>' . htmlspecialchars( $contents, ENT_NOQUOTES ) . "</$element>";
57 }
58 return $out;
59 }
60
70 public static function expandAttributes( $attribs ) {
71 $out = '';
72 if ( $attribs === null ) {
73 return null;
74 } elseif ( is_array( $attribs ) ) {
75 foreach ( $attribs as $name => $val ) {
76 $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
77 }
78 return $out;
79 } else {
80 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
81 }
82 }
83
95 public static function elementClean( $element, $attribs = [], $contents = '' ) {
96 if ( $attribs ) {
97 $attribs = array_map( [ UtfNormal\Validator::class, 'cleanUp' ], $attribs );
98 }
99 if ( $contents ) {
100 $contents =
101 MediaWikiServices::getInstance()->getContentLanguage()->normalize( $contents );
102 }
103 return self::element( $element, $attribs, $contents );
104 }
105
113 public static function openElement( $element, $attribs = null ) {
114 return '<' . $element . self::expandAttributes( $attribs ) . '>';
115 }
116
122 public static function closeElement( $element ) {
123 return "</$element>";
124 }
125
135 public static function tags( $element, $attribs, $contents ) {
136 return self::openElement( $element, $attribs ) . $contents . "</$element>";
137 }
138
148 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
149 global $wgLang;
150 $options = [];
151
152 $data = new XmlSelect( 'month', $id, $selected ?? '' );
153
154 if ( $allmonths !== null ) {
155 $options[wfMessage( 'monthsall' )->text()] = $allmonths;
156 }
157 for ( $i = 1; $i < 13; $i++ ) {
158 $options[$wgLang->getMonthName( $i )] = $i;
159 }
160 $data->addOptions( $options );
161 $data->setAttribute( 'class', 'mw-month-selector' );
162 return $data->getHTML();
163 }
164
171 public static function dateMenu( $year, $month ) {
172 # Offset overrides year/month selection
173 if ( $month && $month !== -1 ) {
174 $encMonth = intval( $month );
175 } else {
176 $encMonth = '';
177 }
178 if ( $year ) {
179 $encYear = intval( $year );
180 } elseif ( $encMonth ) {
181 $timestamp = MWTimestamp::getInstance();
182 $thisMonth = intval( $timestamp->format( 'n' ) );
183 $thisYear = intval( $timestamp->format( 'Y' ) );
184 if ( $encMonth > $thisMonth ) {
185 $thisYear--;
186 }
187 $encYear = $thisYear;
188 } else {
189 $encYear = '';
190 }
191 $inputAttribs = [ 'id' => 'year', 'maxlength' => 4, 'size' => 7 ];
192 return self::label( wfMessage( 'year' )->text(), 'year' ) . ' ' .
193 Html::input( 'year', $encYear, 'number', $inputAttribs ) . ' ' .
194 self::label( wfMessage( 'month' )->text(), 'month' ) . ' ' .
195 self::monthSelector( $encMonth, '-1' );
196 }
197
208 public static function languageSelector( $selected, $customisedOnly = true,
209 $inLanguage = null, $overrideAttrs = [], Message $msg = null
210 ) {
211 $languageCode = MediaWikiServices::getInstance()->getMainConfig()
212 ->get( MainConfigNames::LanguageCode );
213
214 $include = $customisedOnly ? LanguageNameUtils::SUPPORTED : LanguageNameUtils::DEFINED;
215 $languages = MediaWikiServices::getInstance()
216 ->getLanguageNameUtils()
217 ->getLanguageNames( $inLanguage, $include );
218
219 // Make sure the site language is in the list;
220 // a custom language code might not have a defined name...
221 if ( !array_key_exists( $languageCode, $languages ) ) {
222 $languages[$languageCode] = $languageCode;
223 // Sort the array again
224 ksort( $languages );
225 }
226
232 $selected = isset( $languages[$selected] ) ? $selected : $languageCode;
233 $options = "\n";
234 foreach ( $languages as $code => $name ) {
235 $options .= self::option( "$code - $name", $code, $code == $selected ) . "\n";
236 }
237
238 $attrs = [ 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ];
239 $attrs = array_merge( $attrs, $overrideAttrs );
240
241 if ( $msg === null ) {
242 $msg = wfMessage( 'yourlanguage' );
243 }
244 return [
245 self::label( $msg->text(), $attrs['id'] ),
246 self::tags( 'select', $attrs, $options )
247 ];
248 }
249
257 public static function span( $text, $class, $attribs = [] ) {
258 return self::element( 'span', [ 'class' => $class ] + $attribs, $text );
259 }
260
269 public static function wrapClass( $text, $class, $tag = 'span', $attribs = [] ) {
270 return self::tags( $tag, [ 'class' => $class ] + $attribs, $text );
271 }
272
281 public static function input( $name, $size = false, $value = false, $attribs = [] ) {
282 $attributes = [ 'name' => $name ];
283
284 if ( $size ) {
285 $attributes['size'] = $size;
286 }
287
288 if ( $value !== false ) { // maybe 0
289 $attributes['value'] = $value;
290 }
291
292 return self::element( 'input',
293 Html::getTextInputAttributes( $attributes + $attribs ) );
294 }
295
304 public static function password( $name, $size = false, $value = false,
305 $attribs = []
306 ) {
307 return self::input( $name, $size, $value,
308 array_merge( $attribs, [ 'type' => 'password' ] ) );
309 }
310
319 public static function attrib( $name, $present = true ) {
320 return $present ? [ $name => $name ] : [];
321 }
322
330 public static function check( $name, $checked = false, $attribs = [] ) {
331 return self::element( 'input', array_merge(
332 [
333 'name' => $name,
334 'type' => 'checkbox',
335 'value' => 1 ],
336 self::attrib( 'checked', $checked ),
337 $attribs ) );
338 }
339
348 public static function radio( $name, $value, $checked = false, $attribs = [] ) {
349 return self::element( 'input', [
350 'name' => $name,
351 'type' => 'radio',
352 'value' => $value ] + self::attrib( 'checked', $checked ) + $attribs );
353 }
354
365 public static function label( $label, $id, $attribs = [] ) {
366 $a = [ 'for' => $id ];
367
368 foreach ( [ 'class', 'title' ] as $attr ) {
369 if ( isset( $attribs[$attr] ) ) {
370 $a[$attr] = $attribs[$attr];
371 }
372 }
373
374 return self::element( 'label', $a, $label );
375 }
376
387 public static function inputLabel( $label, $name, $id, $size = false,
388 $value = false, $attribs = []
389 ) {
390 [ $label, $input ] = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
391 return $label . "\u{00A0}" . $input;
392 }
393
406 public static function inputLabelSep( $label, $name, $id, $size = false,
407 $value = false, $attribs = []
408 ) {
409 return [
410 self::label( $label, $id, $attribs ),
411 self::input( $name, $size, $value, [ 'id' => $id ] + $attribs )
412 ];
413 }
414
426 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = [] ) {
427 $useMediaWikiUIEverywhere = MediaWikiServices::getInstance()->getMainConfig()
428 ->get( MainConfigNames::UseMediaWikiUIEverywhere );
429 $chkLabel = self::check( $name, $checked, [ 'id' => $id ] + $attribs ) .
430 "\u{00A0}" .
431 self::label( $label, $id, $attribs );
432
433 if ( $useMediaWikiUIEverywhere ) {
434 $chkLabel = self::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
435 $chkLabel . self::closeElement( 'div' );
436 }
437 return $chkLabel;
438 }
439
452 public static function radioLabel( $label, $name, $value, $id,
453 $checked = false, $attribs = []
454 ) {
455 return self::radio( $name, $value, $checked, [ 'id' => $id ] + $attribs ) .
456 "\u{00A0}" .
457 self::label( $label, $id, $attribs );
458 }
459
467 public static function submitButton( $value, $attribs = [] ) {
468 $useMediaWikiUIEverywhere = MediaWikiServices::getInstance()->getMainConfig()
469 ->get( MainConfigNames::UseMediaWikiUIEverywhere );
470 $baseAttrs = [
471 'type' => 'submit',
472 'value' => $value,
473 ];
474 // Done conditionally for time being as it is possible
475 // some submit forms
476 // might need to be mw-ui-destructive (e.g. delete a page)
477 if ( $useMediaWikiUIEverywhere ) {
478 $baseAttrs['class'] = 'mw-ui-button mw-ui-progressive';
479 }
480 // Any custom attributes will take precedence of anything in baseAttrs e.g. override the class
481 $attribs += $baseAttrs;
482 return Html::element( 'input', $attribs );
483 }
484
493 public static function option( $text, $value = null, $selected = false,
494 $attribs = [] ) {
495 if ( $value !== null ) {
496 $attribs['value'] = $value;
497 }
498 if ( $selected ) {
499 $attribs['selected'] = 'selected';
500 }
501 return Html::element( 'option', $attribs, $text );
502 }
503
517 public static function listDropDown( $name = '', $list = '', $other = '',
518 $selected = '', $class = '', $tabindex = null
519 ) {
520 $options = self::listDropDownOptions( $list, [ 'other' => $other ] );
521
522 $xmlSelect = new XmlSelect( $name, $name, $selected );
523 $xmlSelect->addOptions( $options );
524
525 if ( $class ) {
526 $xmlSelect->setAttribute( 'class', $class );
527 }
528 if ( $tabindex ) {
529 $xmlSelect->setAttribute( 'tabindex', $tabindex );
530 }
531
532 return $xmlSelect->getHTML();
533 }
534
548 public static function listDropDownOptions( $list, $params = [] ) {
549 $options = [];
550
551 if ( isset( $params['other'] ) ) {
552 $options[ $params['other'] ] = 'other';
553 }
554
555 $optgroup = false;
556 foreach ( explode( "\n", $list ) as $option ) {
557 $value = trim( $option );
558 if ( $value == '' ) {
559 continue;
560 }
561 if ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
562 # A new group is starting...
563 $value = trim( substr( $value, 1 ) );
564 if ( $value !== '' &&
565 // Do not use the value for 'other' as option group - T251351
566 ( !isset( $params['other'] ) || $value !== $params['other'] )
567 ) {
568 $optgroup = $value;
569 } else {
570 $optgroup = false;
571 }
572 } elseif ( substr( $value, 0, 2 ) == '**' ) {
573 # groupmember
574 $opt = trim( substr( $value, 2 ) );
575 if ( $optgroup === false ) {
576 $options[$opt] = $opt;
577 } else {
578 $options[$optgroup][$opt] = $opt;
579 }
580 } else {
581 # groupless reason list
582 $optgroup = false;
583 $options[$option] = $option;
584 }
585 }
586
587 return $options;
588 }
589
598 public static function listDropDownOptionsOoui( $options ) {
599 $optionsOoui = [];
600
601 foreach ( $options as $text => $value ) {
602 if ( is_array( $value ) ) {
603 $optionsOoui[] = [ 'optgroup' => (string)$text ];
604 foreach ( $value as $text2 => $value2 ) {
605 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
606 }
607 } else {
608 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
609 }
610 }
611
612 return $optionsOoui;
613 }
614
626 public static function fieldset( $legend = false, $content = false, $attribs = [] ) {
627 $s = self::openElement( 'fieldset', $attribs ) . "\n";
628
629 if ( $legend ) {
630 $s .= self::element( 'legend', null, $legend ) . "\n";
631 }
632
633 if ( $content !== false ) {
634 $s .= $content . "\n";
635 $s .= self::closeElement( 'fieldset' ) . "\n";
636 }
637
638 return $s;
639 }
640
652 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = [] ) {
653 return self::element( 'textarea',
654 Html::getTextInputAttributes(
655 [
656 'name' => $name,
657 'id' => $name,
658 'cols' => $cols,
659 'rows' => $rows
660 ] + $attribs
661 ),
662 $content, false );
663 }
664
676 public static function encodeJsVar( $value, $pretty = false ) {
677 if ( $value instanceof XmlJsCode ) {
678 return $value->value;
679 }
680 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
681 }
682
694 public static function encodeJsCall( $name, $args, $pretty = false ) {
695 foreach ( $args as &$arg ) {
696 $arg = self::encodeJsVar( $arg, $pretty );
697 if ( $arg === false ) {
698 return false;
699 }
700 }
701
702 return "$name(" . ( $pretty
703 ? ( ' ' . implode( ', ', $args ) . ' ' )
704 : implode( ',', $args )
705 ) . ");";
706 }
707
719 private static function isWellFormed( $text ) {
720 $parser = xml_parser_create( "UTF-8" );
721
722 # case folding violates XML standard, turn it off
723 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, 0 );
724
725 if ( !xml_parse( $parser, $text, true ) ) {
726 // $err = xml_error_string( xml_get_error_code( $parser ) );
727 // $position = xml_get_current_byte_index( $parser );
728 // $fragment = $this->extractFragment( $html, $position );
729 // $this->mXmlError = "$err at byte $position:\n$fragment";
730 xml_parser_free( $parser );
731 return false;
732 }
733
734 xml_parser_free( $parser );
735
736 return true;
737 }
738
747 public static function isWellFormedXmlFragment( $text ) {
748 $html =
749 Sanitizer::hackDocType() .
750 '<html>' .
751 $text .
752 '</html>';
753
754 return self::isWellFormed( $html );
755 }
756
764 public static function escapeTagsOnly( $in ) {
765 return str_replace(
766 [ '"', '>', '<' ],
767 [ '&quot;', '&gt;', '&lt;' ],
768 $in );
769 }
770
782 public static function buildForm( $fields, $submitLabel = null, $submitAttribs = [] ) {
783 $form = '';
784 $form .= "<table><tbody>";
785
786 foreach ( $fields as $labelmsg => $input ) {
787 $id = "mw-$labelmsg";
788 $form .= self::openElement( 'tr', [ 'id' => $id ] );
789
790 // TODO use a <label> here for accessibility purposes - will need
791 // to either not use a table to build the form, or find the ID of
792 // the input somehow.
793
794 $form .= self::tags( 'td', [ 'class' => 'mw-label' ], wfMessage( $labelmsg )->parse() );
795 $form .= self::openElement( 'td', [ 'class' => 'mw-input' ] )
796 . $input . self::closeElement( 'td' );
797 $form .= self::closeElement( 'tr' );
798 }
799
800 if ( $submitLabel ) {
801 $form .= self::openElement( 'tr' );
802 $form .= self::tags( 'td', [], '' );
803 $form .= self::openElement( 'td', [ 'class' => 'mw-submit' ] )
804 . self::submitButton( wfMessage( $submitLabel )->text(), $submitAttribs )
805 . self::closeElement( 'td' );
806 $form .= self::closeElement( 'tr' );
807 }
808
809 $form .= "</tbody></table>";
810
811 return $form;
812 }
813
820 public static function buildTable( $rows, $attribs = [], $headers = null ) {
821 $s = self::openElement( 'table', $attribs );
822
823 if ( is_array( $headers ) ) {
824 $s .= self::openElement( 'thead', $attribs );
825
826 foreach ( $headers as $id => $header ) {
827 $attribs = [];
828
829 if ( is_string( $id ) ) {
830 $attribs['id'] = $id;
831 }
832
833 $s .= self::element( 'th', $attribs, $header );
834 }
835 $s .= self::closeElement( 'thead' );
836 }
837
838 foreach ( $rows as $id => $row ) {
839 $attribs = [];
840
841 if ( is_string( $id ) ) {
842 $attribs['id'] = $id;
843 }
844
845 $s .= self::buildTableRow( $attribs, $row );
846 }
847
848 $s .= self::closeElement( 'table' );
849
850 return $s;
851 }
852
859 public static function buildTableRow( $attribs, $cells ) {
860 $s = self::openElement( 'tr', $attribs );
861
862 foreach ( $cells as $id => $cell ) {
863 $attribs = [];
864
865 if ( is_string( $id ) ) {
866 $attribs['id'] = $id;
867 }
868
869 $s .= self::element( 'td', $attribs, $cell );
870 }
871
872 $s .= self::closeElement( 'tr' );
873
874 return $s;
875 }
876}
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode $wgLang
Definition Setup.php:527
MediaWiki exception.
This class is a collection of static functions that serve two purposes:
Definition Html.php:55
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.
The Message class deals with fetching and processing of interface message into a variety of formats.
Definition Message.php:144
A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to interpret a given string a...
Definition XmlJsCode.php:40
Class for generating HTML <select> or <datalist> elements.
Definition XmlSelect.php:28
Module of static functions for generating XML.
Definition Xml.php:31
static password( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML password input field.
Definition Xml.php:304
static closeElement( $element)
Shortcut to close an XML element.
Definition Xml.php:122
static textarea( $name, $content, $cols=40, $rows=5, $attribs=[])
Shortcut for creating textareas.
Definition Xml.php:652
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:406
static listDropDownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition Xml.php:548
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition Xml.php:676
static listDropDownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition Xml.php:598
static isWellFormedXmlFragment( $text)
Check if a string is a well-formed XML fragment.
Definition Xml.php:747
static check( $name, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox.
Definition Xml.php:330
static dateMenu( $year, $month)
Definition Xml.php:171
static buildForm( $fields, $submitLabel=null, $submitAttribs=[])
Generate a form (without the opening form element).
Definition Xml.php:782
static attrib( $name, $present=true)
Internal function for use in checkboxes and radio buttons and such.
Definition Xml.php:319
static label( $label, $id, $attribs=[])
Convenience function to build an HTML form label.
Definition Xml.php:365
static openElement( $element, $attribs=null)
This opens an XML element.
Definition Xml.php:113
static input( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field.
Definition Xml.php:281
static wrapClass( $text, $class, $tag='span', $attribs=[])
Shortcut to make a specific element with a class attribute.
Definition Xml.php:269
static buildTable( $rows, $attribs=[], $headers=null)
Definition Xml.php:820
static submitButton( $value, $attribs=[])
Convenience function to build an HTML submit button When $wgUseMediaWikiUIEverywhere is true it will ...
Definition Xml.php:467
static option( $text, $value=null, $selected=false, $attribs=[])
Convenience function to build an HTML drop-down list item.
Definition Xml.php:493
static checkLabel( $label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition Xml.php:426
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:387
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:208
static expandAttributes( $attribs)
Given an array of ('attributename' => 'value'), it generates the code to set the XML attributes : att...
Definition Xml.php:70
static span( $text, $class, $attribs=[])
Shortcut to make a span element.
Definition Xml.php:257
static escapeTagsOnly( $in)
Replace " > and < with their respective HTML entities ( ", >, <)
Definition Xml.php:764
static tags( $element, $attribs, $contents)
Same as Xml::element(), but does not escape contents.
Definition Xml.php:135
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition Xml.php:44
static radio( $name, $value, $checked=false, $attribs=[])
Convenience function to build an HTML radio button.
Definition Xml.php:348
static buildTableRow( $attribs, $cells)
Build a row for a table.
Definition Xml.php:859
static radioLabel( $label, $name, $value, $id, $checked=false, $attribs=[])
Convenience function to build an HTML radio button with a label.
Definition Xml.php:452
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition Xml.php:694
static listDropDown( $name='', $list='', $other='', $selected='', $class='', $tabindex=null)
Build a drop-down box from a textual list.
Definition Xml.php:517
static monthSelector( $selected='', $allmonths=null, $id='month')
Create a date selector.
Definition Xml.php:148
static fieldset( $legend=false, $content=false, $attribs=[])
Shortcut for creating fieldsets.
Definition Xml.php:626
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:95
$content
Definition router.php:76
$header