MediaWiki  master
Xml.php
Go to the documentation of this file.
1 <?php
24 
28 class Xml {
41  public static function element( $element, $attribs = null, $contents = '',
42  $allowShortTag = true
43  ) {
44  $out = '<' . $element;
45  if ( $attribs !== null ) {
46  $out .= self::expandAttributes( $attribs );
47  }
48  if ( $contents === null ) {
49  $out .= '>';
50  } elseif ( $allowShortTag && $contents === '' ) {
51  $out .= ' />';
52  } else {
53  $out .= '>' . htmlspecialchars( $contents, ENT_NOQUOTES ) . "</$element>";
54  }
55  return $out;
56  }
57 
67  public static function expandAttributes( $attribs ) {
68  $out = '';
69  if ( $attribs === null ) {
70  return null;
71  } elseif ( is_array( $attribs ) ) {
72  foreach ( $attribs as $name => $val ) {
73  $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
74  }
75  return $out;
76  } else {
77  throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
78  }
79  }
80 
90  public static function elementClean( $element, $attribs = [], $contents = '' ) {
91  if ( $attribs ) {
92  $attribs = array_map( [ 'UtfNormal\Validator', 'cleanUp' ], $attribs );
93  }
94  if ( $contents ) {
95  $contents =
96  MediaWikiServices::getInstance()->getContentLanguage()->normalize( $contents );
97  }
98  return self::element( $element, $attribs, $contents );
99  }
100 
108  public static function openElement( $element, $attribs = null ) {
109  return '<' . $element . self::expandAttributes( $attribs ) . '>';
110  }
111 
117  public static function closeElement( $element ) {
118  return "</$element>";
119  }
120 
130  public static function tags( $element, $attribs, $contents ) {
131  return self::openElement( $element, $attribs ) . $contents . "</$element>";
132  }
133 
143  public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
144  global $wgLang;
145  $options = [];
146  $data = new XmlSelect( 'month', $id, $selected );
147  if ( $selected === null ) {
148  $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 ( intval( $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  global $wgLanguageCode;
208 
209  $include = $customisedOnly ? 'mwfile' : 'mw';
210  $languages = MediaWikiServices::getInstance()
211  ->getLanguageNameUtils()
212  ->getLanguageNames( $inLanguage, $include );
213 
214  // Make sure the site language is in the list;
215  // a custom language code might not have a defined name...
216  if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
218  // Sort the array again
219  ksort( $languages );
220  }
221 
227  $selected = isset( $languages[$selected] ) ? $selected : $wgLanguageCode;
228  $options = "\n";
229  foreach ( $languages as $code => $name ) {
230  $options .= self::option( "$code - $name", $code, $code == $selected ) . "\n";
231  }
232 
233  $attrs = [ 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ];
234  $attrs = array_merge( $attrs, $overrideAttrs );
235 
236  if ( $msg === null ) {
237  $msg = wfMessage( 'yourlanguage' );
238  }
239  return [
240  self::label( $msg->text(), $attrs['id'] ),
241  self::tags( 'select', $attrs, $options )
242  ];
243  }
244 
252  public static function span( $text, $class, $attribs = [] ) {
253  return self::element( 'span', [ 'class' => $class ] + $attribs, $text );
254  }
255 
264  public static function wrapClass( $text, $class, $tag = 'span', $attribs = [] ) {
265  return self::tags( $tag, [ 'class' => $class ] + $attribs, $text );
266  }
267 
276  public static function input( $name, $size = false, $value = false, $attribs = [] ) {
277  $attributes = [ 'name' => $name ];
278 
279  if ( $size ) {
280  $attributes['size'] = $size;
281  }
282 
283  if ( $value !== false ) { // maybe 0
284  $attributes['value'] = $value;
285  }
286 
287  return self::element( 'input',
288  Html::getTextInputAttributes( $attributes + $attribs ) );
289  }
290 
299  public static function password( $name, $size = false, $value = false,
300  $attribs = []
301  ) {
302  return self::input( $name, $size, $value,
303  array_merge( $attribs, [ 'type' => 'password' ] ) );
304  }
305 
314  public static function attrib( $name, $present = true ) {
315  return $present ? [ $name => $name ] : [];
316  }
317 
325  public static function check( $name, $checked = false, $attribs = [] ) {
326  return self::element( 'input', array_merge(
327  [
328  'name' => $name,
329  'type' => 'checkbox',
330  'value' => 1 ],
331  self::attrib( 'checked', $checked ),
332  $attribs ) );
333  }
334 
343  public static function radio( $name, $value, $checked = false, $attribs = [] ) {
344  return self::element( 'input', [
345  'name' => $name,
346  'type' => 'radio',
347  'value' => $value ] + self::attrib( 'checked', $checked ) + $attribs );
348  }
349 
360  public static function label( $label, $id, $attribs = [] ) {
361  $a = [ 'for' => $id ];
362 
363  foreach ( [ 'class', 'title' ] as $attr ) {
364  if ( isset( $attribs[$attr] ) ) {
365  $a[$attr] = $attribs[$attr];
366  }
367  }
368 
369  return self::element( 'label', $a, $label );
370  }
371 
382  public static function inputLabel( $label, $name, $id, $size = false,
383  $value = false, $attribs = []
384  ) {
385  list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
386  return $label . "\u{00A0}" . $input;
387  }
388 
401  public static function inputLabelSep( $label, $name, $id, $size = false,
402  $value = false, $attribs = []
403  ) {
404  return [
405  self::label( $label, $id, $attribs ),
406  self::input( $name, $size, $value, [ 'id' => $id ] + $attribs )
407  ];
408  }
409 
421  public static function checkLabel( $label, $name, $id, $checked = false, $attribs = [] ) {
423  $chkLabel = self::check( $name, $checked, [ 'id' => $id ] + $attribs ) .
424  "\u{00A0}" .
425  self::label( $label, $id, $attribs );
426 
428  $chkLabel = self::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
429  $chkLabel . self::closeElement( 'div' );
430  }
431  return $chkLabel;
432  }
433 
446  public static function radioLabel( $label, $name, $value, $id,
447  $checked = false, $attribs = []
448  ) {
449  return self::radio( $name, $value, $checked, [ 'id' => $id ] + $attribs ) .
450  "\u{00A0}" .
451  self::label( $label, $id, $attribs );
452  }
453 
461  public static function submitButton( $value, $attribs = [] ) {
463  $baseAttrs = [
464  'type' => 'submit',
465  'value' => $value,
466  ];
467  // Done conditionally for time being as it is possible
468  // some submit forms
469  // might need to be mw-ui-destructive (e.g. delete a page)
471  $baseAttrs['class'] = 'mw-ui-button mw-ui-progressive';
472  }
473  // Any custom attributes will take precendence of anything in baseAttrs e.g. override the class
474  $attribs = $attribs + $baseAttrs;
475  return Html::element( 'input', $attribs );
476  }
477 
486  public static function option( $text, $value = null, $selected = false,
487  $attribs = [] ) {
488  if ( $value !== null ) {
489  $attribs['value'] = $value;
490  }
491  if ( $selected ) {
492  $attribs['selected'] = 'selected';
493  }
494  return Html::element( 'option', $attribs, $text );
495  }
496 
510  public static function listDropDown( $name = '', $list = '', $other = '',
511  $selected = '', $class = '', $tabindex = null
512  ) {
513  $options = self::listDropDownOptions( $list, [ 'other' => $other ] );
514 
515  $xmlSelect = new XmlSelect( $name, $name, $selected );
516  $xmlSelect->addOptions( $options );
517 
518  if ( $class ) {
519  $xmlSelect->setAttribute( 'class', $class );
520  }
521  if ( $tabindex ) {
522  $xmlSelect->setAttribute( 'tabindex', $tabindex );
523  }
524 
525  return $xmlSelect->getHTML();
526  }
527 
541  public static function listDropDownOptions( $list, $params = [] ) {
542  $options = [];
543 
544  if ( isset( $params['other'] ) ) {
545  $options[ $params['other'] ] = 'other';
546  }
547 
548  $optgroup = false;
549  foreach ( explode( "\n", $list ) as $option ) {
550  $value = trim( $option );
551  if ( $value == '' ) {
552  continue;
553  } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
554  # A new group is starting...
555  $value = trim( substr( $value, 1 ) );
556  $optgroup = $value;
557  } elseif ( substr( $value, 0, 2 ) == '**' ) {
558  # groupmember
559  $opt = trim( substr( $value, 2 ) );
560  if ( $optgroup === false ) {
561  $options[$opt] = $opt;
562  } else {
563  $options[$optgroup][$opt] = $opt;
564  }
565  } else {
566  # groupless reason list
567  $optgroup = false;
568  $options[$option] = $option;
569  }
570  }
571 
572  return $options;
573  }
574 
583  public static function listDropDownOptionsOoui( $options ) {
584  $optionsOoui = [];
585 
586  foreach ( $options as $text => $value ) {
587  if ( is_array( $value ) ) {
588  $optionsOoui[] = [ 'optgroup' => (string)$text ];
589  foreach ( $value as $text2 => $value2 ) {
590  $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
591  }
592  } else {
593  $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
594  }
595  }
596 
597  return $optionsOoui;
598  }
599 
611  public static function fieldset( $legend = false, $content = false, $attribs = [] ) {
612  $s = self::openElement( 'fieldset', $attribs ) . "\n";
613 
614  if ( $legend ) {
615  $s .= self::element( 'legend', null, $legend ) . "\n";
616  }
617 
618  if ( $content !== false ) {
619  $s .= $content . "\n";
620  $s .= self::closeElement( 'fieldset' ) . "\n";
621  }
622 
623  return $s;
624  }
625 
637  public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = [] ) {
638  return self::element( 'textarea',
639  Html::getTextInputAttributes(
640  [
641  'name' => $name,
642  'id' => $name,
643  'cols' => $cols,
644  'rows' => $rows
645  ] + $attribs
646  ),
647  $content, false );
648  }
649 
661  public static function encodeJsVar( $value, $pretty = false ) {
662  if ( $value instanceof XmlJsCode ) {
663  return $value->value;
664  }
665  return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
666  }
667 
679  public static function encodeJsCall( $name, $args, $pretty = false ) {
680  foreach ( $args as &$arg ) {
681  $arg = self::encodeJsVar( $arg, $pretty );
682  if ( $arg === false ) {
683  return false;
684  }
685  }
686 
687  return "$name(" . ( $pretty
688  ? ( ' ' . implode( ', ', $args ) . ' ' )
689  : implode( ',', $args )
690  ) . ");";
691  }
692 
704  private static function isWellFormed( $text ) {
705  $parser = xml_parser_create( "UTF-8" );
706 
707  # case folding violates XML standard, turn it off
708  xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
709 
710  if ( !xml_parse( $parser, $text, true ) ) {
711  // $err = xml_error_string( xml_get_error_code( $parser ) );
712  // $position = xml_get_current_byte_index( $parser );
713  // $fragment = $this->extractFragment( $html, $position );
714  // $this->mXmlError = "$err at byte $position:\n$fragment";
715  xml_parser_free( $parser );
716  return false;
717  }
718 
719  xml_parser_free( $parser );
720 
721  return true;
722  }
723 
732  public static function isWellFormedXmlFragment( $text ) {
733  $html =
734  Sanitizer::hackDocType() .
735  '<html>' .
736  $text .
737  '</html>';
738 
739  return self::isWellFormed( $html );
740  }
741 
749  public static function escapeTagsOnly( $in ) {
750  return str_replace(
751  [ '"', '>', '<' ],
752  [ '&quot;', '&gt;', '&lt;' ],
753  $in );
754  }
755 
767  public static function buildForm( $fields, $submitLabel = null, $submitAttribs = [] ) {
768  $form = '';
769  $form .= "<table><tbody>";
770 
771  foreach ( $fields as $labelmsg => $input ) {
772  $id = "mw-$labelmsg";
773  $form .= self::openElement( 'tr', [ 'id' => $id ] );
774 
775  // TODO use a <label> here for accessibility purposes - will need
776  // to either not use a table to build the form, or find the ID of
777  // the input somehow.
778 
779  $form .= self::tags( 'td', [ 'class' => 'mw-label' ], wfMessage( $labelmsg )->parse() );
780  $form .= self::openElement( 'td', [ 'class' => 'mw-input' ] )
781  . $input . self::closeElement( 'td' );
782  $form .= self::closeElement( 'tr' );
783  }
784 
785  if ( $submitLabel ) {
786  $form .= self::openElement( 'tr' );
787  $form .= self::tags( 'td', [], '' );
788  $form .= self::openElement( 'td', [ 'class' => 'mw-submit' ] )
789  . self::submitButton( wfMessage( $submitLabel )->text(), $submitAttribs )
790  . self::closeElement( 'td' );
791  $form .= self::closeElement( 'tr' );
792  }
793 
794  $form .= "</tbody></table>";
795 
796  return $form;
797  }
798 
806  public static function buildTable( $rows, $attribs = [], $headers = null ) {
807  $s = self::openElement( 'table', $attribs );
808 
809  if ( is_array( $headers ) ) {
810  $s .= self::openElement( 'thead', $attribs );
811 
812  foreach ( $headers as $id => $header ) {
813  $attribs = [];
814 
815  if ( is_string( $id ) ) {
816  $attribs['id'] = $id;
817  }
818 
819  $s .= self::element( 'th', $attribs, $header );
820  }
821  $s .= self::closeElement( 'thead' );
822  }
823 
824  foreach ( $rows as $id => $row ) {
825  $attribs = [];
826 
827  if ( is_string( $id ) ) {
828  $attribs['id'] = $id;
829  }
830 
831  $s .= self::buildTableRow( $attribs, $row );
832  }
833 
834  $s .= self::closeElement( 'table' );
835 
836  return $s;
837  }
838 
845  public static function buildTableRow( $attribs, $cells ) {
846  $s = self::openElement( 'tr', $attribs );
847 
848  foreach ( $cells as $id => $cell ) {
849  $attribs = [];
850 
851  if ( is_string( $id ) ) {
852  $attribs['id'] = $id;
853  }
854 
855  $s .= self::element( 'td', $attribs, $cell );
856  }
857 
858  $s .= self::closeElement( 'tr' );
859 
860  return $s;
861  }
862 }
Xml\isWellFormed
static isWellFormed( $text)
Check if a string is well-formed XML.
Definition: Xml.php:704
Xml\buildTableRow
static buildTableRow( $attribs, $cells)
Build a row for a table.
Definition: Xml.php:845
Xml\expandAttributes
static expandAttributes( $attribs)
Given an array of ('attributename' => 'value'), it generates the code to set the XML attributes : att...
Definition: Xml.php:67
Xml\listDropDownOptionsOoui
static listDropDownOptionsOoui( $options)
Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
Definition: Xml.php:583
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:137
Xml\label
static label( $label, $id, $attribs=[])
Convenience function to build an HTML form label.
Definition: Xml.php:360
$languages
switch( $options['output']) $languages
Definition: transstat.php:79
$wgUseMediaWikiUIEverywhere
$wgUseMediaWikiUIEverywhere
Temporary variable that applies MediaWiki UI wherever it can be supported.
Definition: DefaultSettings.php:3309
Xml\textarea
static textarea( $name, $content, $cols=40, $rows=5, $attribs=[])
Shortcut for creating textareas.
Definition: Xml.php:637
Xml\radio
static radio( $name, $value, $checked=false, $attribs=[])
Convenience function to build an HTML radio button.
Definition: Xml.php:343
Xml\inputLabelSep
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:401
Xml\option
static option( $text, $value=null, $selected=false, $attribs=[])
Convenience function to build an HTML drop-down list item.
Definition: Xml.php:486
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1201
$s
$s
Definition: mergeMessageFileList.php:185
Message
Xml\password
static password( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML password input field.
Definition: Xml.php:299
Xml\buildForm
static buildForm( $fields, $submitLabel=null, $submitAttribs=[])
Generate a form (without the opening form element).
Definition: Xml.php:767
Xml\openElement
static openElement( $element, $attribs=null)
This opens an XML element.
Definition: Xml.php:108
Xml\encodeJsVar
static encodeJsVar( $value, $pretty=false)
Encode a variable of arbitrary type to JavaScript.
Definition: Xml.php:661
Xml\languageSelector
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
FormatJson\UTF8_OK
const UTF8_OK
Skip escaping most characters above U+007F for readability and compactness.
Definition: FormatJson.php:34
XmlSelect
Class for generating HTML <select> or <datalist> elements.
Definition: XmlSelect.php:26
Xml\fieldset
static fieldset( $legend=false, $content=false, $attribs=[])
Shortcut for creating fieldsets.
Definition: Xml.php:611
XmlJsCode
A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to interpret a given string a...
Definition: XmlJsCode.php:40
Xml\encodeJsCall
static encodeJsCall( $name, $args, $pretty=false)
Create a call to a JavaScript function.
Definition: Xml.php:679
Xml\elementClean
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:90
FormatJson\encode
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:115
Xml\wrapClass
static wrapClass( $text, $class, $tag='span', $attribs=[])
Shortcut to make a specific element with a class attribute.
Definition: Xml.php:264
MWException
MediaWiki exception.
Definition: MWException.php:26
Xml\check
static check( $name, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox.
Definition: Xml.php:325
$wgLang
$wgLang
Definition: Setup.php:776
Xml\element
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:41
$args
if( $line===false) $args
Definition: mcc.php:124
MWTimestamp\getInstance
static getInstance( $ts=false)
Get a timestamp instance in GMT.
Definition: MWTimestamp.php:39
$content
$content
Definition: router.php:78
$header
$header
Definition: updateCredits.php:41
Xml\tags
static tags( $element, $attribs, $contents)
Same as Xml::element(), but does not escape contents.
Definition: Xml.php:130
Xml\attrib
static attrib( $name, $present=true)
Internal function for use in checkboxes and radio buttons and such.
Definition: Xml.php:314
$wgLanguageCode
$wgLanguageCode
Site language code.
Definition: DefaultSettings.php:2998
Xml\span
static span( $text, $class, $attribs=[])
Shortcut to make a span element.
Definition: Xml.php:252
Xml\radioLabel
static radioLabel( $label, $name, $value, $id, $checked=false, $attribs=[])
Convenience function to build an HTML radio button with a label.
Definition: Xml.php:446
Xml\closeElement
static closeElement( $element)
Shortcut to close an XML element.
Definition: Xml.php:117
Xml\listDropDown
static listDropDown( $name='', $list='', $other='', $selected='', $class='', $tabindex=null)
Build a drop-down box from a textual list.
Definition: Xml.php:510
Xml\isWellFormedXmlFragment
static isWellFormedXmlFragment( $text)
Check if a string is a well-formed XML fragment.
Definition: Xml.php:732
Xml\dateMenu
static dateMenu( $year, $month)
Definition: Xml.php:167
Xml\input
static input( $name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field.
Definition: Xml.php:276
Xml\buildTable
static buildTable( $rows, $attribs=[], $headers=null)
Build a table of data.
Definition: Xml.php:806
Xml\monthSelector
static monthSelector( $selected='', $allmonths=null, $id='month')
Create a date selector.
Definition: Xml.php:143
Xml\inputLabel
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:382
Xml
Module of static functions for generating XML.
Definition: Xml.php:28
Xml\escapeTagsOnly
static escapeTagsOnly( $in)
Replace " > and < with their respective HTML entities ( ", >, <)
Definition: Xml.php:749
Xml\listDropDownOptions
static listDropDownOptions( $list, $params=[])
Build options for a drop-down box from a textual list.
Definition: Xml.php:541
Xml\submitButton
static submitButton( $value, $attribs=[])
Convenience function to build an HTML submit button When $wgUseMediaWikiUIEverywhere is true it will ...
Definition: Xml.php:461
Xml\checkLabel
static checkLabel( $label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition: Xml.php:421