MediaWiki  master
Xml.php
Go to the documentation of this file.
1 <?php
27 
31 class 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 
69  public static function expandAttributes( ?array $attribs ) {
70  if ( $attribs === null ) {
71  return null;
72  }
73  $out = '';
74  foreach ( $attribs as $name => $val ) {
75  $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
76  }
77  return $out;
78  }
79 
91  public static function elementClean( $element, $attribs = [], $contents = '' ) {
92  if ( $attribs ) {
93  $attribs = array_map( [ UtfNormal\Validator::class, 'cleanUp' ], $attribs );
94  }
95  if ( $contents ) {
96  $contents =
97  MediaWikiServices::getInstance()->getContentLanguage()->normalize( $contents );
98  }
99  return self::element( $element, $attribs, $contents );
100  }
101 
109  public static function openElement( $element, $attribs = null ) {
110  return '<' . $element . self::expandAttributes( $attribs ) . '>';
111  }
112 
118  public static function closeElement( $element ) {
119  return "</$element>";
120  }
121 
131  public static function tags( $element, $attribs, $contents ) {
132  return self::openElement( $element, $attribs ) . $contents . "</$element>";
133  }
134 
144  public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
145  global $wgLang;
146  $options = [];
147 
148  $data = new XmlSelect( 'month', $id, $selected ?? '' );
149 
150  if ( $allmonths !== null ) {
151  $options[wfMessage( 'monthsall' )->text()] = $allmonths;
152  }
153  for ( $i = 1; $i < 13; $i++ ) {
154  $options[$wgLang->getMonthName( $i )] = $i;
155  }
156  $data->addOptions( $options );
157  $data->setAttribute( 'class', 'mw-month-selector' );
158  return $data->getHTML();
159  }
160 
167  public static function dateMenu( $year, $month ) {
168  # Offset overrides year/month selection
169  if ( $month && $month !== -1 ) {
170  $encMonth = intval( $month );
171  } else {
172  $encMonth = '';
173  }
174  if ( $year ) {
175  $encYear = intval( $year );
176  } elseif ( $encMonth ) {
177  $timestamp = MWTimestamp::getInstance();
178  $thisMonth = intval( $timestamp->format( 'n' ) );
179  $thisYear = intval( $timestamp->format( 'Y' ) );
180  if ( $encMonth > $thisMonth ) {
181  $thisYear--;
182  }
183  $encYear = $thisYear;
184  } else {
185  $encYear = '';
186  }
187  $inputAttribs = [ 'id' => 'year', 'maxlength' => 4, 'size' => 7 ];
188  return self::label( wfMessage( 'year' )->text(), 'year' ) . ' ' .
189  Html::input( 'year', $encYear, 'number', $inputAttribs ) . ' ' .
190  self::label( wfMessage( 'month' )->text(), 'month' ) . ' ' .
191  self::monthSelector( $encMonth, '-1' );
192  }
193 
204  public static function languageSelector( $selected, $customisedOnly = true,
205  $inLanguage = null, $overrideAttrs = [], Message $msg = null
206  ) {
207  $languageCode = MediaWikiServices::getInstance()->getMainConfig()
208  ->get( MainConfigNames::LanguageCode );
209 
210  $include = $customisedOnly ? LanguageNameUtils::SUPPORTED : LanguageNameUtils::DEFINED;
211  $languages = MediaWikiServices::getInstance()
212  ->getLanguageNameUtils()
213  ->getLanguageNames( $inLanguage, $include );
214 
215  // Make sure the site language is in the list;
216  // a custom language code might not have a defined name...
217  if ( !array_key_exists( $languageCode, $languages ) ) {
218  $languages[$languageCode] = $languageCode;
219  // Sort the array again
220  ksort( $languages );
221  }
222 
228  $selected = isset( $languages[$selected] ) ? $selected : $languageCode;
229  $options = "\n";
230  foreach ( $languages as $code => $name ) {
231  $options .= self::option( "$code - $name", $code, $code == $selected ) . "\n";
232  }
233 
234  $attrs = [ 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ];
235  $attrs = array_merge( $attrs, $overrideAttrs );
236 
237  if ( $msg === null ) {
238  $msg = wfMessage( 'yourlanguage' );
239  }
240  return [
241  self::label( $msg->text(), $attrs['id'] ),
242  self::tags( 'select', $attrs, $options )
243  ];
244  }
245 
253  public static function span( $text, $class, $attribs = [] ) {
254  return self::element( 'span', [ 'class' => $class ] + $attribs, $text );
255  }
256 
265  public static function wrapClass( $text, $class, $tag = 'span', $attribs = [] ) {
266  return self::tags( $tag, [ 'class' => $class ] + $attribs, $text );
267  }
268 
277  public static function input( $name, $size = false, $value = false, $attribs = [] ) {
278  $attributes = [ 'name' => $name ];
279 
280  if ( $size ) {
281  $attributes['size'] = $size;
282  }
283 
284  if ( $value !== false ) { // maybe 0
285  $attributes['value'] = $value;
286  }
287 
288  return self::element( 'input',
289  Html::getTextInputAttributes( $attributes + $attribs ) );
290  }
291 
300  public static function password( $name, $size = false, $value = false,
301  $attribs = []
302  ) {
303  return self::input( $name, $size, $value,
304  array_merge( $attribs, [ 'type' => 'password' ] ) );
305  }
306 
315  public static function attrib( $name, $present = true ) {
316  return $present ? [ $name => $name ] : [];
317  }
318 
326  public static function check( $name, $checked = false, $attribs = [] ) {
327  return self::element( 'input', array_merge(
328  [
329  'name' => $name,
330  'type' => 'checkbox',
331  'value' => 1 ],
332  self::attrib( 'checked', $checked ),
333  $attribs ) );
334  }
335 
344  public static function radio( $name, $value, $checked = false, $attribs = [] ) {
345  return self::element( 'input', [
346  'name' => $name,
347  'type' => 'radio',
348  'value' => $value ] + self::attrib( 'checked', $checked ) + $attribs );
349  }
350 
361  public static function label( $label, $id, $attribs = [] ) {
362  $a = [ 'for' => $id ];
363 
364  foreach ( [ 'class', 'title' ] as $attr ) {
365  if ( isset( $attribs[$attr] ) ) {
366  $a[$attr] = $attribs[$attr];
367  }
368  }
369 
370  return self::element( 'label', $a, $label );
371  }
372 
383  public static function inputLabel( $label, $name, $id, $size = false,
384  $value = false, $attribs = []
385  ) {
386  [ $label, $input ] = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
387  return $label . "\u{00A0}" . $input;
388  }
389 
402  public static function inputLabelSep( $label, $name, $id, $size = false,
403  $value = false, $attribs = []
404  ) {
405  return [
406  self::label( $label, $id, $attribs ),
407  self::input( $name, $size, $value, [ 'id' => $id ] + $attribs )
408  ];
409  }
410 
422  public static function checkLabel( $label, $name, $id, $checked = false, $attribs = [] ) {
423  $useMediaWikiUIEverywhere = MediaWikiServices::getInstance()->getMainConfig()
424  ->get( MainConfigNames::UseMediaWikiUIEverywhere );
425  $chkLabel = self::check( $name, $checked, [ 'id' => $id ] + $attribs ) .
426  "\u{00A0}" .
427  self::label( $label, $id, $attribs );
428 
429  if ( $useMediaWikiUIEverywhere ) {
430  $chkLabel = self::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
431  $chkLabel . self::closeElement( 'div' );
432  }
433  return $chkLabel;
434  }
435 
448  public static function radioLabel( $label, $name, $value, $id,
449  $checked = false, $attribs = []
450  ) {
451  return self::radio( $name, $value, $checked, [ 'id' => $id ] + $attribs ) .
452  "\u{00A0}" .
453  self::label( $label, $id, $attribs );
454  }
455 
463  public static function submitButton( $value, $attribs = [] ) {
464  $useMediaWikiUIEverywhere = MediaWikiServices::getInstance()->getMainConfig()
465  ->get( MainConfigNames::UseMediaWikiUIEverywhere );
466  $baseAttrs = [
467  'type' => 'submit',
468  'value' => $value,
469  ];
470  // Done conditionally for time being as it is possible
471  // some submit forms
472  // might need to be mw-ui-destructive (e.g. delete a page)
473  if ( $useMediaWikiUIEverywhere ) {
474  $baseAttrs['class'] = 'mw-ui-button mw-ui-progressive';
475  }
476  // Any custom attributes will take precedence of anything in baseAttrs e.g. override the class
477  $attribs += $baseAttrs;
478  return Html::element( 'input', $attribs );
479  }
480 
489  public static function option( $text, $value = null, $selected = false,
490  $attribs = [] ) {
491  if ( $value !== null ) {
492  $attribs['value'] = $value;
493  }
494  if ( $selected ) {
495  $attribs['selected'] = 'selected';
496  }
497  return Html::element( 'option', $attribs, $text );
498  }
499 
513  public static function listDropDown( $name = '', $list = '', $other = '',
514  $selected = '', $class = '', $tabindex = null
515  ) {
516  $options = self::listDropDownOptions( $list, [ 'other' => $other ] );
517 
518  $xmlSelect = new XmlSelect( $name, $name, $selected );
519  $xmlSelect->addOptions( $options );
520 
521  if ( $class ) {
522  $xmlSelect->setAttribute( 'class', $class );
523  }
524  if ( $tabindex ) {
525  $xmlSelect->setAttribute( 'tabindex', $tabindex );
526  }
527 
528  return $xmlSelect->getHTML();
529  }
530 
544  public static function listDropDownOptions( $list, $params = [] ) {
545  $options = [];
546 
547  if ( isset( $params['other'] ) ) {
548  $options[ $params['other'] ] = 'other';
549  }
550 
551  $optgroup = false;
552  foreach ( explode( "\n", $list ) as $option ) {
553  $value = trim( $option );
554  if ( $value == '' ) {
555  continue;
556  }
557  if ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
558  # A new group is starting...
559  $value = trim( substr( $value, 1 ) );
560  if ( $value !== '' &&
561  // Do not use the value for 'other' as option group - T251351
562  ( !isset( $params['other'] ) || $value !== $params['other'] )
563  ) {
564  $optgroup = $value;
565  } else {
566  $optgroup = false;
567  }
568  } elseif ( substr( $value, 0, 2 ) == '**' ) {
569  # groupmember
570  $opt = trim( substr( $value, 2 ) );
571  if ( $optgroup === false ) {
572  $options[$opt] = $opt;
573  } else {
574  $options[$optgroup][$opt] = $opt;
575  }
576  } else {
577  # groupless reason list
578  $optgroup = false;
579  $options[$option] = $option;
580  }
581  }
582 
583  return $options;
584  }
585 
594  public static function listDropDownOptionsOoui( $options ) {
595  $optionsOoui = [];
596 
597  foreach ( $options as $text => $value ) {
598  if ( is_array( $value ) ) {
599  $optionsOoui[] = [ 'optgroup' => (string)$text ];
600  foreach ( $value as $text2 => $value2 ) {
601  $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
602  }
603  } else {
604  $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
605  }
606  }
607 
608  return $optionsOoui;
609  }
610 
622  public static function fieldset( $legend = false, $content = false, $attribs = [] ) {
623  $s = self::openElement( 'fieldset', $attribs ) . "\n";
624 
625  if ( $legend ) {
626  $s .= self::element( 'legend', null, $legend ) . "\n";
627  }
628 
629  if ( $content !== false ) {
630  $s .= $content . "\n";
631  $s .= self::closeElement( 'fieldset' ) . "\n";
632  }
633 
634  return $s;
635  }
636 
648  public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = [] ) {
649  return self::element( 'textarea',
650  Html::getTextInputAttributes(
651  [
652  'name' => $name,
653  'id' => $name,
654  'cols' => $cols,
655  'rows' => $rows
656  ] + $attribs
657  ),
658  $content, false );
659  }
660 
672  public static function encodeJsVar( $value, $pretty = false ) {
673  if ( $value instanceof XmlJsCode ) {
674  return $value->value;
675  }
676  return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
677  }
678 
690  public static function encodeJsCall( $name, $args, $pretty = false ) {
691  foreach ( $args as &$arg ) {
692  $arg = self::encodeJsVar( $arg, $pretty );
693  if ( $arg === false ) {
694  return false;
695  }
696  }
697 
698  return "$name(" . ( $pretty
699  ? ( ' ' . implode( ', ', $args ) . ' ' )
700  : implode( ',', $args )
701  ) . ");";
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 =
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 
778  public static function buildForm( $fields, $submitLabel = null, $submitAttribs = [] ) {
779  $form = '';
780  $form .= "<table><tbody>";
781 
782  foreach ( $fields as $labelmsg => $input ) {
783  $id = "mw-$labelmsg";
784  $form .= self::openElement( 'tr', [ 'id' => $id ] );
785 
786  // TODO use a <label> here for accessibility purposes - will need
787  // to either not use a table to build the form, or find the ID of
788  // the input somehow.
789 
790  $form .= self::tags( 'td', [ 'class' => 'mw-label' ], wfMessage( $labelmsg )->parse() );
791  $form .= self::openElement( 'td', [ 'class' => 'mw-input' ] )
792  . $input . self::closeElement( 'td' );
793  $form .= self::closeElement( 'tr' );
794  }
795 
796  if ( $submitLabel ) {
797  $form .= self::openElement( 'tr' );
798  $form .= self::tags( 'td', [], '' );
799  $form .= self::openElement( 'td', [ 'class' => 'mw-submit' ] )
800  . self::submitButton( wfMessage( $submitLabel )->text(), $submitAttribs )
801  . self::closeElement( 'td' );
802  $form .= self::closeElement( 'tr' );
803  }
804 
805  $form .= "</tbody></table>";
806 
807  return $form;
808  }
809 
816  public static function buildTable( $rows, $attribs = [], $headers = null ) {
817  $s = self::openElement( 'table', $attribs );
818 
819  if ( is_array( $headers ) ) {
820  $s .= self::openElement( 'thead', $attribs );
821 
822  foreach ( $headers as $id => $header ) {
823  $attribs = [];
824 
825  if ( is_string( $id ) ) {
826  $attribs['id'] = $id;
827  }
828 
829  $s .= self::element( 'th', $attribs, $header );
830  }
831  $s .= self::closeElement( 'thead' );
832  }
833 
834  foreach ( $rows as $id => $row ) {
835  $attribs = [];
836 
837  if ( is_string( $id ) ) {
838  $attribs['id'] = $id;
839  }
840 
841  $s .= self::buildTableRow( $attribs, $row );
842  }
843 
844  $s .= self::closeElement( 'table' );
845 
846  return $s;
847  }
848 
855  public static function buildTableRow( $attribs, $cells ) {
856  $s = self::openElement( 'tr', $attribs );
857 
858  foreach ( $cells as $id => $cell ) {
859  $attribs = [];
860 
861  if ( is_string( $id ) ) {
862  $attribs['id'] = $id;
863  }
864 
865  $s .= self::element( 'td', $attribs, $cell );
866  }
867 
868  $s .= self::closeElement( 'tr' );
869 
870  return $s;
871  }
872 }
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) $wgLang
Definition: Setup.php:529
const UTF8_OK
Skip escaping most characters above U+007F for readability and compactness.
Definition: FormatJson.php:34
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:96
static getInstance( $ts=false)
Get a timestamp instance in GMT.
Definition: MWTimestamp.php:48
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
static encodeAttribute( $text)
Encode an attribute value for HTML output.
Definition: Sanitizer.php:859
static hackDocType()
Hack up a private DOCTYPE with HTML's standard entity declarations.
Definition: Sanitizer.php:1753
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:300
static closeElement( $element)
Shortcut to close an XML element.
Definition: Xml.php:118
static textarea( $name, $content, $cols=40, $rows=5, $attribs=[])
Shortcut for creating textareas.
Definition: Xml.php:648
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:402
static listDropDownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition: Xml.php:544
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition: Xml.php:672
static listDropDownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition: Xml.php:594
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:326
static dateMenu( $year, $month)
Definition: Xml.php:167
static buildForm( $fields, $submitLabel=null, $submitAttribs=[])
Generate a form (without the opening form element).
Definition: Xml.php:778
static attrib( $name, $present=true)
Internal function for use in checkboxes and radio buttons and such.
Definition: Xml.php:315
static label( $label, $id, $attribs=[])
Convenience function to build an HTML form label.
Definition: Xml.php:361
static openElement( $element, $attribs=null)
This opens an XML element.
Definition: Xml.php:109
static input( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field.
Definition: Xml.php:277
static wrapClass( $text, $class, $tag='span', $attribs=[])
Shortcut to make a specific element with a class attribute.
Definition: Xml.php:265
static buildTable( $rows, $attribs=[], $headers=null)
Definition: Xml.php:816
static submitButton( $value, $attribs=[])
Convenience function to build an HTML submit button When $wgUseMediaWikiUIEverywhere is true it will ...
Definition: Xml.php:463
static option( $text, $value=null, $selected=false, $attribs=[])
Convenience function to build an HTML drop-down list item.
Definition: Xml.php:489
static checkLabel( $label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition: Xml.php:422
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:383
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:204
static span( $text, $class, $attribs=[])
Shortcut to make a span element.
Definition: Xml.php:253
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:131
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:344
static buildTableRow( $attribs, $cells)
Build a row for a table.
Definition: Xml.php:855
static radioLabel( $label, $name, $value, $id, $checked=false, $attribs=[])
Convenience function to build an HTML radio button with a label.
Definition: Xml.php:448
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition: Xml.php:690
static listDropDown( $name='', $list='', $other='', $selected='', $class='', $tabindex=null)
Build a drop-down box from a textual list.
Definition: Xml.php:513
static expandAttributes(?array $attribs)
Given an array of ('attributename' => 'value'), it generates the code to set the XML attributes : att...
Definition: Xml.php:69
static monthSelector( $selected='', $allmonths=null, $id='month')
Create a date selector.
Definition: Xml.php:144
static fieldset( $legend=false, $content=false, $attribs=[])
Shortcut for creating fieldsets.
Definition: Xml.php:622
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:91
$content
Definition: router.php:76
$header