Merge "RevisionStoreDbTestBase, remove redundant needsDB override"
[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 } else {
51 if ( $allowShortTag && $contents === '' ) {
52 $out .= ' />';
53 } else {
54 $out .= '>' . htmlspecialchars( $contents, ENT_NOQUOTES ) . "</$element>";
55 }
56 }
57 return $out;
58 }
59
60 /**
61 * Given an array of ('attributename' => 'value'), it generates the code
62 * to set the XML attributes : attributename="value".
63 * The values are passed to Sanitizer::encodeAttribute.
64 * Returns null or empty string if no attributes given.
65 * @param array|null $attribs Array of attributes for an XML element
66 * @throws MWException
67 * @return null|string
68 */
69 public static function expandAttributes( $attribs ) {
70 $out = '';
71 if ( is_null( $attribs ) ) {
72 return null;
73 } elseif ( is_array( $attribs ) ) {
74 foreach ( $attribs as $name => $val ) {
75 $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
76 }
77 return $out;
78 } else {
79 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
80 }
81 }
82
83 /**
84 * Format an XML element as with self::element(), but run text through the content language's
85 * normalize() validator first to ensure that no invalid UTF-8 is passed.
86 *
87 * @param string $element
88 * @param array $attribs Name=>value pairs. Values will be escaped.
89 * @param string $contents Null to make an open tag only; '' for a contentless closed tag (default)
90 * @return string
91 */
92 public static function elementClean( $element, $attribs = [], $contents = '' ) {
93 if ( $attribs ) {
94 $attribs = array_map( [ 'UtfNormal\Validator', 'cleanUp' ], $attribs );
95 }
96 if ( $contents ) {
97 $contents =
98 MediaWikiServices::getInstance()->getContentLanguage()->normalize( $contents );
99 }
100 return self::element( $element, $attribs, $contents );
101 }
102
103 /**
104 * This opens an XML element
105 *
106 * @param string $element Name of the element
107 * @param array|null $attribs Array of attributes, see Xml::expandAttributes()
108 * @return string
109 */
110 public static function openElement( $element, $attribs = null ) {
111 return '<' . $element . self::expandAttributes( $attribs ) . '>';
112 }
113
114 /**
115 * Shortcut to close an XML element
116 * @param string $element Element name
117 * @return string
118 */
119 public static function closeElement( $element ) {
120 return "</$element>";
121 }
122
123 /**
124 * Same as Xml::element(), but does not escape contents. Handy when the
125 * content you have is already valid xml.
126 *
127 * @param string $element Element name
128 * @param array|null $attribs Array of attributes
129 * @param string $contents Content of the element
130 * @return string
131 */
132 public static function tags( $element, $attribs, $contents ) {
133 return self::openElement( $element, $attribs ) . $contents . "</$element>";
134 }
135
136 /**
137 * Create a date selector
138 *
139 * @param string $selected The month which should be selected, default ''.
140 * @param string|null $allmonths Value of a special item denoting all month.
141 * Null to not include (default).
142 * @param string $id Element identifier
143 * @return string Html string containing the month selector
144 */
145 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
146 global $wgLang;
147 $options = [];
148 $data = new XmlSelect( 'month', $id, $selected );
149 if ( is_null( $selected ) ) {
150 $selected = '';
151 }
152 if ( !is_null( $allmonths ) ) {
153 $options[wfMessage( 'monthsall' )->text()] = $allmonths;
154 }
155 for ( $i = 1; $i < 13; $i++ ) {
156 $options[$wgLang->getMonthName( $i )] = $i;
157 }
158 $data->addOptions( $options );
159 $data->setAttribute( 'class', 'mw-month-selector' );
160 return $data->getHTML();
161 }
162
163 /**
164 * @param int|string $year Use '' or 0 to start with no year preselected.
165 * @param int|string $month A month in the 1..12 range. Use '', 0 or -1 to start with no month
166 * preselected.
167 * @return string Formatted HTML
168 */
169 public static function dateMenu( $year, $month ) {
170 # Offset overrides year/month selection
171 if ( $month && $month !== -1 ) {
172 $encMonth = intval( $month );
173 } else {
174 $encMonth = '';
175 }
176 if ( $year ) {
177 $encYear = intval( $year );
178 } elseif ( $encMonth ) {
179 $timestamp = MWTimestamp::getInstance();
180 $thisMonth = intval( $timestamp->format( 'n' ) );
181 $thisYear = intval( $timestamp->format( 'Y' ) );
182 if ( intval( $encMonth ) > $thisMonth ) {
183 $thisYear--;
184 }
185 $encYear = $thisYear;
186 } else {
187 $encYear = '';
188 }
189 $inputAttribs = [ 'id' => 'year', 'maxlength' => 4, 'size' => 7 ];
190 return self::label( wfMessage( 'year' )->text(), 'year' ) . ' ' .
191 Html::input( 'year', $encYear, 'number', $inputAttribs ) . ' ' .
192 self::label( wfMessage( 'month' )->text(), 'month' ) . ' ' .
193 self::monthSelector( $encMonth, -1 );
194 }
195
196 /**
197 * Construct a language selector appropriate for use in a form or preferences
198 *
199 * @param string $selected The language code of the selected language
200 * @param bool $customisedOnly If true only languages which have some content are listed
201 * @param string|null $inLanguage The ISO code of the language to display the select list in
202 * @param array $overrideAttrs Override the attributes of the select tag (since 1.20)
203 * @param Message|null $msg Label message key (since 1.20)
204 * @return array Array containing 2 items: label HTML and select list HTML
205 */
206 public static function languageSelector( $selected, $customisedOnly = true,
207 $inLanguage = null, $overrideAttrs = [], Message $msg = null
208 ) {
209 global $wgLanguageCode;
210
211 $include = $customisedOnly ? 'mwfile' : 'mw';
212 $languages = Language::fetchLanguageNames( $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 ) ) {
217 $languages[$wgLanguageCode] = $wgLanguageCode;
218 // Sort the array again
219 ksort( $languages );
220 }
221
222 /**
223 * If a bogus value is set, default to the content language.
224 * Otherwise, no default is selected and the user ends up
225 * with Afrikaans since it's first in the list.
226 */
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
245 /**
246 * Shortcut to make a span element
247 * @param string $text Content of the element, will be escaped
248 * @param string $class Class name of the span element
249 * @param array $attribs Other attributes
250 * @return string
251 */
252 public static function span( $text, $class, $attribs = [] ) {
253 return self::element( 'span', [ 'class' => $class ] + $attribs, $text );
254 }
255
256 /**
257 * Shortcut to make a specific element with a class attribute
258 * @param string $text Content of the element, will be escaped
259 * @param string $class Class name of the span element
260 * @param string $tag Element name
261 * @param array $attribs Other attributes
262 * @return string
263 */
264 public static function wrapClass( $text, $class, $tag = 'span', $attribs = [] ) {
265 return self::tags( $tag, [ 'class' => $class ] + $attribs, $text );
266 }
267
268 /**
269 * Convenience function to build an HTML text input field
270 * @param string $name Value of the name attribute
271 * @param int $size Value of the size attribute
272 * @param mixed $value Value of the value attribute
273 * @param array $attribs Other attributes
274 * @return string HTML
275 */
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
291 /**
292 * Convenience function to build an HTML password input field
293 * @param string $name Value of the name attribute
294 * @param int $size Value of the size attribute
295 * @param mixed $value Value of the value attribute
296 * @param array $attribs Other attributes
297 * @return string HTML
298 */
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
306 /**
307 * Internal function for use in checkboxes and radio buttons and such.
308 *
309 * @param string $name
310 * @param bool $present
311 *
312 * @return array
313 */
314 public static function attrib( $name, $present = true ) {
315 return $present ? [ $name => $name ] : [];
316 }
317
318 /**
319 * Convenience function to build an HTML checkbox
320 * @param string $name Value of the name attribute
321 * @param bool $checked Whether the checkbox is checked or not
322 * @param array $attribs Array other attributes
323 * @return string HTML
324 */
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
335 /**
336 * Convenience function to build an HTML radio button
337 * @param string $name Value of the name attribute
338 * @param string $value Value of the value attribute
339 * @param bool $checked Whether the checkbox is checked or not
340 * @param array $attribs Other attributes
341 * @return string HTML
342 */
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
350 /**
351 * Convenience function to build an HTML form label
352 * @param string $label Text of the label
353 * @param string $id
354 * @param array $attribs An attribute array. This will usually be
355 * the same array as is passed to the corresponding input element,
356 * so this function will cherry-pick appropriate attributes to
357 * apply to the label as well; only class and title are applied.
358 * @return string HTML
359 */
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
372 /**
373 * Convenience function to build an HTML text input field with a label
374 * @param string $label Text of the label
375 * @param string $name Value of the name attribute
376 * @param string $id Id of the input
377 * @param int|bool $size Value of the size attribute
378 * @param string|bool $value Value of the value attribute
379 * @param array $attribs Other attributes
380 * @return string HTML
381 */
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
389 /**
390 * Same as Xml::inputLabel() but return input and label in an array
391 *
392 * @param string $label
393 * @param string $name
394 * @param string $id
395 * @param int|bool $size
396 * @param string|bool $value
397 * @param array $attribs
398 *
399 * @return array
400 */
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
410 /**
411 * Convenience function to build an HTML checkbox with a label
412 *
413 * @param string $label
414 * @param string $name
415 * @param string $id
416 * @param bool $checked
417 * @param array $attribs
418 *
419 * @return string HTML
420 */
421 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = [] ) {
422 global $wgUseMediaWikiUIEverywhere;
423 $chkLabel = self::check( $name, $checked, [ 'id' => $id ] + $attribs ) .
424 "\u{00A0}" .
425 self::label( $label, $id, $attribs );
426
427 if ( $wgUseMediaWikiUIEverywhere ) {
428 $chkLabel = self::openElement( 'div', [ 'class' => 'mw-ui-checkbox' ] ) .
429 $chkLabel . self::closeElement( 'div' );
430 }
431 return $chkLabel;
432 }
433
434 /**
435 * Convenience function to build an HTML radio button with a label
436 *
437 * @param string $label
438 * @param string $name
439 * @param string $value
440 * @param string $id
441 * @param bool $checked
442 * @param array $attribs
443 *
444 * @return string HTML
445 */
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
454 /**
455 * Convenience function to build an HTML submit button
456 * When $wgUseMediaWikiUIEverywhere is true it will default to a progressive button
457 * @param string $value Label text for the button (unescaped)
458 * @param array $attribs Optional custom attributes
459 * @return string HTML
460 */
461 public static function submitButton( $value, $attribs = [] ) {
462 global $wgUseMediaWikiUIEverywhere;
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)
470 if ( $wgUseMediaWikiUIEverywhere ) {
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
478 /**
479 * Convenience function to build an HTML drop-down list item.
480 * @param string $text Text for this item. Will be HTML escaped
481 * @param string|null $value Form submission value; if empty, use text
482 * @param bool $selected If true, will be the default selected item
483 * @param array $attribs Optional additional HTML attributes
484 * @return string HTML
485 */
486 public static function option( $text, $value = null, $selected = false,
487 $attribs = [] ) {
488 if ( !is_null( $value ) ) {
489 $attribs['value'] = $value;
490 }
491 if ( $selected ) {
492 $attribs['selected'] = 'selected';
493 }
494 return Html::element( 'option', $attribs, $text );
495 }
496
497 /**
498 * Build a drop-down box from a textual list. This is a wrapper
499 * for Xml::listDropDownOptions() plus the XmlSelect class.
500 *
501 * @param string $name Name and id for the drop-down
502 * @param string $list Correctly formatted text (newline delimited) to be
503 * used to generate the options.
504 * @param string $other Text for the "Other reasons" option
505 * @param string $selected Option which should be pre-selected
506 * @param string $class CSS classes for the drop-down
507 * @param int|null $tabindex Value of the tabindex attribute
508 * @return string
509 */
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
528 /**
529 * Build options for a drop-down box from a textual list.
530 *
531 * The result of this function can be passed to XmlSelect::addOptions()
532 * (to render a plain `<select>` dropdown box) or to Xml::listDropDownOptionsOoui()
533 * and then OOUI\DropdownInputWidget() (to render a pretty one).
534 *
535 * @param string $list Correctly formatted text (newline delimited) to be
536 * used to generate the options.
537 * @param array $params Extra parameters:
538 * - string $params['other'] If set, add an option with this as text and a value of 'other'
539 * @return array Array keys are textual labels, values are internal values
540 */
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
575 /**
576 * Convert options for a drop-down box into a format accepted by OOUI\DropdownInputWidget etc.
577 *
578 * TODO Find a better home for this function.
579 *
580 * @param array $options Options, as returned e.g. by Xml::listDropDownOptions()
581 * @return array
582 */
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
600 /**
601 * Shortcut for creating fieldsets.
602 *
603 * @param string|bool $legend Legend of the fieldset. If evaluates to false,
604 * legend is not added.
605 * @param string $content Pre-escaped content for the fieldset. If false,
606 * only open fieldset is returned.
607 * @param array $attribs Any attributes to fieldset-element.
608 *
609 * @return string
610 */
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
626 /**
627 * Shortcut for creating textareas.
628 *
629 * @param string $name The 'name' for the textarea
630 * @param string $content Content for the textarea
631 * @param int $cols The number of columns for the textarea
632 * @param int $rows The number of rows for the textarea
633 * @param array $attribs Any other attributes for the textarea
634 *
635 * @return string
636 */
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
650 /**
651 * Encode a variable of arbitrary type to JavaScript.
652 * If the value is an XmlJsCode object, pass through the object's value verbatim.
653 *
654 * @note Only use this function for generating JavaScript code. If generating output
655 * for a proper JSON parser, just call FormatJson::encode() directly.
656 *
657 * @param mixed $value The value being encoded. Can be any type except a resource.
658 * @param bool $pretty If true, add non-significant whitespace to improve readability.
659 * @return string|bool String if successful; false upon failure
660 */
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
668 /**
669 * Create a call to a JavaScript function. The supplied arguments will be
670 * encoded using Xml::encodeJsVar().
671 *
672 * @since 1.17
673 * @param string $name The name of the function to call, or a JavaScript expression
674 * which evaluates to a function object which is called.
675 * @param array $args The arguments to pass to the function.
676 * @param bool $pretty If true, add non-significant whitespace to improve readability.
677 * @return string|bool String if successful; false upon failure
678 */
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
693 /**
694 * Check if a string is well-formed XML.
695 * Must include the surrounding tag.
696 * This function is a DoS vector if an attacker can define
697 * entities in $text.
698 *
699 * @param string $text String to test.
700 * @return bool
701 *
702 * @todo Error position reporting return
703 */
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
724 /**
725 * Check if a string is a well-formed XML fragment.
726 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
727 * and can use HTML named entities.
728 *
729 * @param string $text
730 * @return bool
731 */
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
742 /**
743 * Replace " > and < with their respective HTML entities ( &quot;,
744 * &gt;, &lt;)
745 *
746 * @param string $in Text that might contain HTML tags.
747 * @return string Escaped string
748 */
749 public static function escapeTagsOnly( $in ) {
750 return str_replace(
751 [ '"', '>', '<' ],
752 [ '&quot;', '&gt;', '&lt;' ],
753 $in );
754 }
755
756 /**
757 * Generate a form (without the opening form element).
758 * Output optionally includes a submit button.
759 * @param array $fields Associative array, key is the name of a message that
760 * contains a description for the field, value is an HTML string
761 * containing the appropriate input.
762 * @param string|null $submitLabel The name of a message containing a label for
763 * the submit button.
764 * @param array $submitAttribs The attributes to add to the submit button
765 * @return string HTML form.
766 */
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
799 /**
800 * Build a table of data
801 * @param array $rows An array of arrays of strings, each to be a row in a table
802 * @param array $attribs An array of attributes to apply to the table tag [optional]
803 * @param array|null $headers An array of strings to use as table headers [optional]
804 * @return string
805 */
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
839 /**
840 * Build a row for a table
841 * @param array $attribs An array of attributes to apply to the tr tag
842 * @param array $cells An array of strings to put in <td>
843 * @return string
844 */
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 }