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