Split parser related files to have one class in one file
[lhc/web/wiklou.git] / includes / Xml.php
1 <?php
2 /**
3 * Methods to generate XML.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * Module of static functions for generating XML
27 */
28 class Xml {
29 /**
30 * Format an XML element with given attributes and, optionally, text content.
31 * Element and attribute names are assumed to be ready for literal inclusion.
32 * Strings are assumed to not contain XML-illegal characters; special
33 * characters (<, >, &) are escaped but illegals are not touched.
34 *
35 * @param string $element Element name
36 * @param array|null $attribs Name=>value pairs. Values will be escaped.
37 * @param string $contents Null to make an open tag only; '' for a contentless closed tag (default)
38 * @param bool $allowShortTag Whether '' in $contents will result in a contentless closed tag
39 * @return string
40 */
41 public static function element( $element, $attribs = null, $contents = '',
42 $allowShortTag = true
43 ) {
44 $out = '<' . $element;
45 if ( !is_null( $attribs ) ) {
46 $out .= self::expandAttributes( $attribs );
47 }
48 if ( is_null( $contents ) ) {
49 $out .= '>';
50 } elseif ( $allowShortTag && $contents === '' ) {
51 $out .= ' />';
52 } else {
53 $out .= '>' . htmlspecialchars( $contents, ENT_NOQUOTES ) . "</$element>";
54 }
55 return $out;
56 }
57
58 /**
59 * Given an array of ('attributename' => 'value'), it generates the code
60 * to set the XML attributes : attributename="value".
61 * The values are passed to Sanitizer::encodeAttribute.
62 * Returns null or empty string if no attributes given.
63 * @param array|null $attribs Array of attributes for an XML element
64 * @throws MWException
65 * @return null|string
66 */
67 public static function expandAttributes( $attribs ) {
68 $out = '';
69 if ( is_null( $attribs ) ) {
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
81 /**
82 * Format an XML element as with self::element(), but run text through the content language's
83 * normalize() validator first to ensure that no invalid UTF-8 is passed.
84 *
85 * @param string $element
86 * @param array $attribs Name=>value pairs. Values will be escaped.
87 * @param string $contents Null to make an open tag only; '' for a contentless closed tag (default)
88 * @return string
89 */
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
101 /**
102 * This opens an XML element
103 *
104 * @param string $element Name of the element
105 * @param array|null $attribs Array of attributes, see Xml::expandAttributes()
106 * @return string
107 */
108 public static function openElement( $element, $attribs = null ) {
109 return '<' . $element . self::expandAttributes( $attribs ) . '>';
110 }
111
112 /**
113 * Shortcut to close an XML element
114 * @param string $element Element name
115 * @return string
116 */
117 public static function closeElement( $element ) {
118 return "</$element>";
119 }
120
121 /**
122 * Same as Xml::element(), but does not escape contents. Handy when the
123 * content you have is already valid xml.
124 *
125 * @param string $element Element name
126 * @param array|null $attribs Array of attributes
127 * @param string $contents Content of the element
128 * @return string
129 */
130 public static function tags( $element, $attribs, $contents ) {
131 return self::openElement( $element, $attribs ) . $contents . "</$element>";
132 }
133
134 /**
135 * Create a date selector
136 *
137 * @param string $selected The month which should be selected, default ''.
138 * @param string|null $allmonths Value of a special item denoting all month.
139 * Null to not include (default).
140 * @param string $id Element identifier
141 * @return string Html string containing the month selector
142 */
143 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
144 global $wgLang;
145 $options = [];
146 $data = new XmlSelect( 'month', $id, $selected );
147 if ( is_null( $selected ) ) {
148 $selected = '';
149 }
150 if ( !is_null( $allmonths ) ) {
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
161 /**
162 * @param int|string $year Use '' or 0 to start with no year preselected.
163 * @param int|string $month A month in the 1..12 range. Use '', 0 or -1 to start with no month
164 * preselected.
165 * @return string Formatted HTML
166 */
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
194 /**
195 * Construct a language selector appropriate for use in a form or preferences
196 *
197 * @param string $selected The language code of the selected language
198 * @param bool $customisedOnly If true only languages which have some content are listed
199 * @param string|null $inLanguage The ISO code of the language to display the select list in
200 * @param array $overrideAttrs Override the attributes of the select tag (since 1.20)
201 * @param Message|null $msg Label message key (since 1.20)
202 * @return array Array containing 2 items: label HTML and select list HTML
203 */
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 = Language::fetchLanguageNames( $inLanguage, $include );
211
212 // Make sure the site language is in the list;
213 // a custom language code might not have a defined name...
214 if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
215 $languages[$wgLanguageCode] = $wgLanguageCode;
216 // Sort the array again
217 ksort( $languages );
218 }
219
220 /**
221 * If a bogus value is set, default to the content language.
222 * Otherwise, no default is selected and the user ends up
223 * with Afrikaans since it's first in the list.
224 */
225 $selected = isset( $languages[$selected] ) ? $selected : $wgLanguageCode;
226 $options = "\n";
227 foreach ( $languages as $code => $name ) {
228 $options .= self::option( "$code - $name", $code, $code == $selected ) . "\n";
229 }
230
231 $attrs = [ 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ];
232 $attrs = array_merge( $attrs, $overrideAttrs );
233
234 if ( $msg === null ) {
235 $msg = wfMessage( 'yourlanguage' );
236 }
237 return [
238 self::label( $msg->text(), $attrs['id'] ),
239 self::tags( 'select', $attrs, $options )
240 ];
241 }
242
243 /**
244 * Shortcut to make a span element
245 * @param string $text Content of the element, will be escaped
246 * @param string $class Class name of the span element
247 * @param array $attribs Other attributes
248 * @return string
249 */
250 public static function span( $text, $class, $attribs = [] ) {
251 return self::element( 'span', [ 'class' => $class ] + $attribs, $text );
252 }
253
254 /**
255 * Shortcut to make a specific element with a class attribute
256 * @param string $text Content of the element, will be escaped
257 * @param string $class Class name of the span element
258 * @param string $tag Element name
259 * @param array $attribs Other attributes
260 * @return string
261 */
262 public static function wrapClass( $text, $class, $tag = 'span', $attribs = [] ) {
263 return self::tags( $tag, [ 'class' => $class ] + $attribs, $text );
264 }
265
266 /**
267 * Convenience function to build an HTML text input field
268 * @param string $name Value of the name attribute
269 * @param int $size Value of the size attribute
270 * @param mixed $value Value of the value attribute
271 * @param array $attribs Other attributes
272 * @return string HTML
273 */
274 public static function input( $name, $size = false, $value = false, $attribs = [] ) {
275 $attributes = [ 'name' => $name ];
276
277 if ( $size ) {
278 $attributes['size'] = $size;
279 }
280
281 if ( $value !== false ) { // maybe 0
282 $attributes['value'] = $value;
283 }
284
285 return self::element( 'input',
286 Html::getTextInputAttributes( $attributes + $attribs ) );
287 }
288
289 /**
290 * Convenience function to build an HTML password input field
291 * @param string $name Value of the name attribute
292 * @param int $size Value of the size attribute
293 * @param mixed $value Value of the value attribute
294 * @param array $attribs Other attributes
295 * @return string HTML
296 */
297 public static function password( $name, $size = false, $value = false,
298 $attribs = []
299 ) {
300 return self::input( $name, $size, $value,
301 array_merge( $attribs, [ 'type' => 'password' ] ) );
302 }
303
304 /**
305 * Internal function for use in checkboxes and radio buttons and such.
306 *
307 * @param string $name
308 * @param bool $present
309 *
310 * @return array
311 */
312 public static function attrib( $name, $present = true ) {
313 return $present ? [ $name => $name ] : [];
314 }
315
316 /**
317 * Convenience function to build an HTML checkbox
318 * @param string $name Value of the name attribute
319 * @param bool $checked Whether the checkbox is checked or not
320 * @param array $attribs Array other attributes
321 * @return string HTML
322 */
323 public static function check( $name, $checked = false, $attribs = [] ) {
324 return self::element( 'input', array_merge(
325 [
326 'name' => $name,
327 'type' => 'checkbox',
328 'value' => 1 ],
329 self::attrib( 'checked', $checked ),
330 $attribs ) );
331 }
332
333 /**
334 * Convenience function to build an HTML radio button
335 * @param string $name Value of the name attribute
336 * @param string $value Value of the value attribute
337 * @param bool $checked Whether the checkbox is checked or not
338 * @param array $attribs Other attributes
339 * @return string HTML
340 */
341 public static function radio( $name, $value, $checked = false, $attribs = [] ) {
342 return self::element( 'input', [
343 'name' => $name,
344 'type' => 'radio',
345 'value' => $value ] + self::attrib( 'checked', $checked ) + $attribs );
346 }
347
348 /**
349 * Convenience function to build an HTML form label
350 * @param string $label Text of the label
351 * @param string $id
352 * @param array $attribs An attribute array. This will usually be
353 * the same array as is passed to the corresponding input element,
354 * so this function will cherry-pick appropriate attributes to
355 * apply to the label as well; only class and title are applied.
356 * @return string HTML
357 */
358 public static function label( $label, $id, $attribs = [] ) {
359 $a = [ 'for' => $id ];
360
361 foreach ( [ 'class', 'title' ] as $attr ) {
362 if ( isset( $attribs[$attr] ) ) {
363 $a[$attr] = $attribs[$attr];
364 }
365 }
366
367 return self::element( 'label', $a, $label );
368 }
369
370 /**
371 * Convenience function to build an HTML text input field with a label
372 * @param string $label Text of the label
373 * @param string $name Value of the name attribute
374 * @param string $id Id of the input
375 * @param int|bool $size Value of the size attribute
376 * @param string|bool $value Value of the value attribute
377 * @param array $attribs Other attributes
378 * @return string HTML
379 */
380 public static function inputLabel( $label, $name, $id, $size = false,
381 $value = false, $attribs = []
382 ) {
383 list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
384 return $label . "\u{00A0}" . $input;
385 }
386
387 /**
388 * Same as Xml::inputLabel() but return input and label in an array
389 *
390 * @param string $label
391 * @param string $name
392 * @param string $id
393 * @param int|bool $size
394 * @param string|bool $value
395 * @param array $attribs
396 *
397 * @return array
398 */
399 public static function inputLabelSep( $label, $name, $id, $size = false,
400 $value = false, $attribs = []
401 ) {
402 return [
403 self::label( $label, $id, $attribs ),
404 self::input( $name, $size, $value, [ 'id' => $id ] + $attribs )
405 ];
406 }
407
408 /**
409 * Convenience function to build an HTML checkbox with a label
410 *
411 * @param string $label
412 * @param string $name
413 * @param string $id
414 * @param bool $checked
415 * @param array $attribs
416 *
417 * @return string HTML
418 */
419 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = [] ) {
420 global $wgUseMediaWikiUIEverywhere;
421 $chkLabel = self::check( $name, $checked, [ 'id' => $id ] + $attribs ) .
422 "\u{00A0}" .
423 self::label( $label, $id, $attribs );
424
425 if ( $wgUseMediaWikiUIEverywhere ) {
426 $chkLabel = self::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
427 $chkLabel . self::closeElement( 'div' );
428 }
429 return $chkLabel;
430 }
431
432 /**
433 * Convenience function to build an HTML radio button with a label
434 *
435 * @param string $label
436 * @param string $name
437 * @param string $value
438 * @param string $id
439 * @param bool $checked
440 * @param array $attribs
441 *
442 * @return string HTML
443 */
444 public static function radioLabel( $label, $name, $value, $id,
445 $checked = false, $attribs = []
446 ) {
447 return self::radio( $name, $value, $checked, [ 'id' => $id ] + $attribs ) .
448 "\u{00A0}" .
449 self::label( $label, $id, $attribs );
450 }
451
452 /**
453 * Convenience function to build an HTML submit button
454 * When $wgUseMediaWikiUIEverywhere is true it will default to a progressive button
455 * @param string $value Label text for the button (unescaped)
456 * @param array $attribs Optional custom attributes
457 * @return string HTML
458 */
459 public static function submitButton( $value, $attribs = [] ) {
460 global $wgUseMediaWikiUIEverywhere;
461 $baseAttrs = [
462 'type' => 'submit',
463 'value' => $value,
464 ];
465 // Done conditionally for time being as it is possible
466 // some submit forms
467 // might need to be mw-ui-destructive (e.g. delete a page)
468 if ( $wgUseMediaWikiUIEverywhere ) {
469 $baseAttrs['class'] = 'mw-ui-button mw-ui-progressive';
470 }
471 // Any custom attributes will take precendence of anything in baseAttrs e.g. override the class
472 $attribs = $attribs + $baseAttrs;
473 return Html::element( 'input', $attribs );
474 }
475
476 /**
477 * Convenience function to build an HTML drop-down list item.
478 * @param string $text Text for this item. Will be HTML escaped
479 * @param string|null $value Form submission value; if empty, use text
480 * @param bool $selected If true, will be the default selected item
481 * @param array $attribs Optional additional HTML attributes
482 * @return string HTML
483 */
484 public static function option( $text, $value = null, $selected = false,
485 $attribs = [] ) {
486 if ( !is_null( $value ) ) {
487 $attribs['value'] = $value;
488 }
489 if ( $selected ) {
490 $attribs['selected'] = 'selected';
491 }
492 return Html::element( 'option', $attribs, $text );
493 }
494
495 /**
496 * Build a drop-down box from a textual list. This is a wrapper
497 * for Xml::listDropDownOptions() plus the XmlSelect class.
498 *
499 * @param string $name Name and id for the drop-down
500 * @param string $list Correctly formatted text (newline delimited) to be
501 * used to generate the options.
502 * @param string $other Text for the "Other reasons" option
503 * @param string $selected Option which should be pre-selected
504 * @param string $class CSS classes for the drop-down
505 * @param int|null $tabindex Value of the tabindex attribute
506 * @return string
507 */
508 public static function listDropDown( $name = '', $list = '', $other = '',
509 $selected = '', $class = '', $tabindex = null
510 ) {
511 $options = self::listDropDownOptions( $list, [ 'other' => $other ] );
512
513 $xmlSelect = new XmlSelect( $name, $name, $selected );
514 $xmlSelect->addOptions( $options );
515
516 if ( $class ) {
517 $xmlSelect->setAttribute( 'class', $class );
518 }
519 if ( $tabindex ) {
520 $xmlSelect->setAttribute( 'tabindex', $tabindex );
521 }
522
523 return $xmlSelect->getHTML();
524 }
525
526 /**
527 * Build options for a drop-down box from a textual list.
528 *
529 * The result of this function can be passed to XmlSelect::addOptions()
530 * (to render a plain `<select>` dropdown box) or to Xml::listDropDownOptionsOoui()
531 * and then OOUI\DropdownInputWidget() (to render a pretty one).
532 *
533 * @param string $list Correctly formatted text (newline delimited) to be
534 * used to generate the options.
535 * @param array $params Extra parameters:
536 * - string $params['other'] If set, add an option with this as text and a value of 'other'
537 * @return array Array keys are textual labels, values are internal values
538 */
539 public static function listDropDownOptions( $list, $params = [] ) {
540 $options = [];
541
542 if ( isset( $params['other'] ) ) {
543 $options[ $params['other'] ] = 'other';
544 }
545
546 $optgroup = false;
547 foreach ( explode( "\n", $list ) as $option ) {
548 $value = trim( $option );
549 if ( $value == '' ) {
550 continue;
551 } elseif ( substr( $value, 0, 1 ) == '*' && substr( $value, 1, 1 ) != '*' ) {
552 # A new group is starting...
553 $value = trim( substr( $value, 1 ) );
554 $optgroup = $value;
555 } elseif ( substr( $value, 0, 2 ) == '**' ) {
556 # groupmember
557 $opt = trim( substr( $value, 2 ) );
558 if ( $optgroup === false ) {
559 $options[$opt] = $opt;
560 } else {
561 $options[$optgroup][$opt] = $opt;
562 }
563 } else {
564 # groupless reason list
565 $optgroup = false;
566 $options[$option] = $option;
567 }
568 }
569
570 return $options;
571 }
572
573 /**
574 * Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
575 *
576 * TODO Find a better home for this function.
577 *
578 * @param array $options Options, as returned e.g. by Xml::listDropDownOptions()
579 * @return array
580 */
581 public static function listDropDownOptionsOoui( $options ) {
582 $optionsOoui = [];
583
584 foreach ( $options as $text => $value ) {
585 if ( is_array( $value ) ) {
586 $optionsOoui[] = [ 'optgroup' => (string)$text ];
587 foreach ( $value as $text2 => $value2 ) {
588 $optionsOoui[] = [ 'data' => (string)$value2, 'label' => (string)$text2 ];
589 }
590 } else {
591 $optionsOoui[] = [ 'data' => (string)$value, 'label' => (string)$text ];
592 }
593 }
594
595 return $optionsOoui;
596 }
597
598 /**
599 * Shortcut for creating fieldsets.
600 *
601 * @param string|bool $legend Legend of the fieldset. If evaluates to false,
602 * legend is not added.
603 * @param string $content Pre-escaped content for the fieldset. If false,
604 * only open fieldset is returned.
605 * @param array $attribs Any attributes to fieldset-element.
606 *
607 * @return string
608 */
609 public static function fieldset( $legend = false, $content = false, $attribs = [] ) {
610 $s = self::openElement( 'fieldset', $attribs ) . "\n";
611
612 if ( $legend ) {
613 $s .= self::element( 'legend', null, $legend ) . "\n";
614 }
615
616 if ( $content !== false ) {
617 $s .= $content . "\n";
618 $s .= self::closeElement( 'fieldset' ) . "\n";
619 }
620
621 return $s;
622 }
623
624 /**
625 * Shortcut for creating textareas.
626 *
627 * @param string $name The 'name' for the textarea
628 * @param string $content Content for the textarea
629 * @param int $cols The number of columns for the textarea
630 * @param int $rows The number of rows for the textarea
631 * @param array $attribs Any other attributes for the textarea
632 *
633 * @return string
634 */
635 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = [] ) {
636 return self::element( 'textarea',
637 Html::getTextInputAttributes(
638 [
639 'name' => $name,
640 'id' => $name,
641 'cols' => $cols,
642 'rows' => $rows
643 ] + $attribs
644 ),
645 $content, false );
646 }
647
648 /**
649 * Encode a variable of arbitrary type to JavaScript.
650 * If the value is an XmlJsCode object, pass through the object's value verbatim.
651 *
652 * @note Only use this function for generating JavaScript code. If generating output
653 * for a proper JSON parser, just call FormatJson::encode() directly.
654 *
655 * @param mixed $value The value being encoded. Can be any type except a resource.
656 * @param bool $pretty If true, add non-significant whitespace to improve readability.
657 * @return string|bool String if successful; false upon failure
658 */
659 public static function encodeJsVar( $value, $pretty = false ) {
660 if ( $value instanceof XmlJsCode ) {
661 return $value->value;
662 }
663 return FormatJson::encode( $value, $pretty, FormatJson::UTF8_OK );
664 }
665
666 /**
667 * Create a call to a JavaScript function. The supplied arguments will be
668 * encoded using Xml::encodeJsVar().
669 *
670 * @since 1.17
671 * @param string $name The name of the function to call, or a JavaScript expression
672 * which evaluates to a function object which is called.
673 * @param array $args The arguments to pass to the function.
674 * @param bool $pretty If true, add non-significant whitespace to improve readability.
675 * @return string|bool String if successful; false upon failure
676 */
677 public static function encodeJsCall( $name, $args, $pretty = false ) {
678 foreach ( $args as &$arg ) {
679 $arg = self::encodeJsVar( $arg, $pretty );
680 if ( $arg === false ) {
681 return false;
682 }
683 }
684
685 return "$name(" . ( $pretty
686 ? ( ' ' . implode( ', ', $args ) . ' ' )
687 : implode( ',', $args )
688 ) . ");";
689 }
690
691 /**
692 * Check if a string is well-formed XML.
693 * Must include the surrounding tag.
694 * This function is a DoS vector if an attacker can define
695 * entities in $text.
696 *
697 * @param string $text String to test.
698 * @return bool
699 *
700 * @todo Error position reporting return
701 */
702 private static function isWellFormed( $text ) {
703 $parser = xml_parser_create( "UTF-8" );
704
705 # case folding violates XML standard, turn it off
706 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
707
708 if ( !xml_parse( $parser, $text, true ) ) {
709 // $err = xml_error_string( xml_get_error_code( $parser ) );
710 // $position = xml_get_current_byte_index( $parser );
711 // $fragment = $this->extractFragment( $html, $position );
712 // $this->mXmlError = "$err at byte $position:\n$fragment";
713 xml_parser_free( $parser );
714 return false;
715 }
716
717 xml_parser_free( $parser );
718
719 return true;
720 }
721
722 /**
723 * Check if a string is a well-formed XML fragment.
724 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
725 * and can use HTML named entities.
726 *
727 * @param string $text
728 * @return bool
729 */
730 public static function isWellFormedXmlFragment( $text ) {
731 $html =
732 Sanitizer::hackDocType() .
733 '<html>' .
734 $text .
735 '</html>';
736
737 return self::isWellFormed( $html );
738 }
739
740 /**
741 * Replace " > and < with their respective HTML entities ( &quot;,
742 * &gt;, &lt;)
743 *
744 * @param string $in Text that might contain HTML tags.
745 * @return string Escaped string
746 */
747 public static function escapeTagsOnly( $in ) {
748 return str_replace(
749 [ '"', '>', '<' ],
750 [ '&quot;', '&gt;', '&lt;' ],
751 $in );
752 }
753
754 /**
755 * Generate a form (without the opening form element).
756 * Output optionally includes a submit button.
757 * @param array $fields Associative array, key is the name of a message that
758 * contains a description for the field, value is an HTML string
759 * containing the appropriate input.
760 * @param string|null $submitLabel The name of a message containing a label for
761 * the submit button.
762 * @param array $submitAttribs The attributes to add to the submit button
763 * @return string HTML form.
764 */
765 public static function buildForm( $fields, $submitLabel = null, $submitAttribs = [] ) {
766 $form = '';
767 $form .= "<table><tbody>";
768
769 foreach ( $fields as $labelmsg => $input ) {
770 $id = "mw-$labelmsg";
771 $form .= self::openElement( 'tr', [ 'id' => $id ] );
772
773 // TODO use a <label> here for accessibility purposes - will need
774 // to either not use a table to build the form, or find the ID of
775 // the input somehow.
776
777 $form .= self::tags( 'td', [ 'class' => 'mw-label' ], wfMessage( $labelmsg )->parse() );
778 $form .= self::openElement( 'td', [ 'class' => 'mw-input' ] )
779 . $input . self::closeElement( 'td' );
780 $form .= self::closeElement( 'tr' );
781 }
782
783 if ( $submitLabel ) {
784 $form .= self::openElement( 'tr' );
785 $form .= self::tags( 'td', [], '' );
786 $form .= self::openElement( 'td', [ 'class' => 'mw-submit' ] )
787 . self::submitButton( wfMessage( $submitLabel )->text(), $submitAttribs )
788 . self::closeElement( 'td' );
789 $form .= self::closeElement( 'tr' );
790 }
791
792 $form .= "</tbody></table>";
793
794 return $form;
795 }
796
797 /**
798 * Build a table of data
799 * @param array $rows An array of arrays of strings, each to be a row in a table
800 * @param array $attribs An array of attributes to apply to the table tag [optional]
801 * @param array|null $headers An array of strings to use as table headers [optional]
802 * @return string
803 */
804 public static function buildTable( $rows, $attribs = [], $headers = null ) {
805 $s = self::openElement( 'table', $attribs );
806
807 if ( is_array( $headers ) ) {
808 $s .= self::openElement( 'thead', $attribs );
809
810 foreach ( $headers as $id => $header ) {
811 $attribs = [];
812
813 if ( is_string( $id ) ) {
814 $attribs['id'] = $id;
815 }
816
817 $s .= self::element( 'th', $attribs, $header );
818 }
819 $s .= self::closeElement( 'thead' );
820 }
821
822 foreach ( $rows as $id => $row ) {
823 $attribs = [];
824
825 if ( is_string( $id ) ) {
826 $attribs['id'] = $id;
827 }
828
829 $s .= self::buildTableRow( $attribs, $row );
830 }
831
832 $s .= self::closeElement( 'table' );
833
834 return $s;
835 }
836
837 /**
838 * Build a row for a table
839 * @param array $attribs An array of attributes to apply to the tr tag
840 * @param array $cells An array of strings to put in <td>
841 * @return string
842 */
843 public static function buildTableRow( $attribs, $cells ) {
844 $s = self::openElement( 'tr', $attribs );
845
846 foreach ( $cells as $id => $cell ) {
847 $attribs = [];
848
849 if ( is_string( $id ) ) {
850 $attribs['id'] = $id;
851 }
852
853 $s .= self::element( 'td', $attribs, $cell );
854 }
855
856 $s .= self::closeElement( 'tr' );
857
858 return $s;
859 }
860 }