Merge "(bug 37755) Set robot meta tags for 'view source' pages"
[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 $element String: element name
34 * @param $attribs Array: Name=>value pairs. Values will be escaped.
35 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
36 * @param $allowShortTag Bool: whether '' in $contents will result in a contentless closed tag
37 * @return string
38 */
39 public static function element( $element, $attribs = null, $contents = '', $allowShortTag = true ) {
40 $out = '<' . $element;
41 if( !is_null( $attribs ) ) {
42 $out .= self::expandAttributes( $attribs );
43 }
44 if( is_null( $contents ) ) {
45 $out .= '>';
46 } else {
47 if( $allowShortTag && $contents === '' ) {
48 $out .= ' />';
49 } else {
50 $out .= '>' . htmlspecialchars( $contents ) . "</$element>";
51 }
52 }
53 return $out;
54 }
55
56 /**
57 * Given an array of ('attributename' => 'value'), it generates the code
58 * to set the XML attributes : attributename="value".
59 * The values are passed to Sanitizer::encodeAttribute.
60 * Return null if no attributes given.
61 * @param $attribs Array of attributes for an XML element
62 * @throws MWException
63 * @return null|string
64 */
65 public static function expandAttributes( $attribs ) {
66 $out = '';
67 if( is_null( $attribs ) ) {
68 return null;
69 } elseif( is_array( $attribs ) ) {
70 foreach( $attribs as $name => $val ) {
71 $out .= " {$name}=\"" . Sanitizer::encodeAttribute( $val ) . '"';
72 }
73 return $out;
74 } else {
75 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
76 }
77 }
78
79 /**
80 * Format an XML element as with self::element(), but run text through the
81 * $wgContLang->normalize() validator first to ensure that no invalid UTF-8
82 * is passed.
83 *
84 * @param $element String:
85 * @param $attribs Array: Name=>value pairs. Values will be escaped.
86 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
87 * @return string
88 */
89 public static function elementClean( $element, $attribs = array(), $contents = '') {
90 global $wgContLang;
91 if( $attribs ) {
92 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
93 }
94 if( $contents ) {
95 wfProfileIn( __METHOD__ . '-norm' );
96 $contents = $wgContLang->normalize( $contents );
97 wfProfileOut( __METHOD__ . '-norm' );
98 }
99 return self::element( $element, $attribs, $contents );
100 }
101
102 /**
103 * This opens an XML element
104 *
105 * @param $element String name of the element
106 * @param $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 $element String element name
116 * @return string
117 */
118 public static function closeElement( $element ) { return "</$element>"; }
119
120 /**
121 * Same as Xml::element(), but does not escape contents. Handy when the
122 * content you have is already valid xml.
123 *
124 * @param $element String element name
125 * @param $attribs array of attributes
126 * @param $contents String content of the element
127 * @return string
128 */
129 public static function tags( $element, $attribs = null, $contents ) {
130 return self::openElement( $element, $attribs ) . $contents . "</$element>";
131 }
132
133 /**
134 * Build a drop-down box for selecting a namespace
135 *
136 * @param $selected Mixed: Namespace which should be pre-selected
137 * @param $all Mixed: Value of an item denoting all namespaces, or null to omit
138 * @param $element_name String: value of the "name" attribute of the select tag
139 * @param $label String: optional label to add to the field
140 * @return string
141 * @deprecated since 1.19
142 */
143 public static function namespaceSelector( $selected = '', $all = null, $element_name = 'namespace', $label = null ) {
144 wfDeprecated( __METHOD__, '1.19' );
145 return Html::namespaceSelector( array(
146 'selected' => $selected,
147 'all' => $all,
148 'label' => $label,
149 ), array(
150 'name' => $element_name,
151 'id' => 'namespace',
152 'class' => 'namespaceselector',
153 ) );
154 }
155
156 /**
157 * Create a date selector
158 *
159 * @param $selected Mixed: the month which should be selected, default ''
160 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
161 * @param $id String: Element identifier
162 * @return String: Html string containing the month selector
163 */
164 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
165 global $wgLang;
166 $options = array();
167 if( is_null( $selected ) )
168 $selected = '';
169 if( !is_null( $allmonths ) )
170 $options[] = self::option( wfMessage( 'monthsall' )->text(), $allmonths, $selected === $allmonths );
171 for( $i = 1; $i < 13; $i++ )
172 $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
173 return self::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
174 . implode( "\n", $options )
175 . self::closeElement( 'select' );
176 }
177
178 /**
179 * @param $year Integer
180 * @param $month Integer
181 * @return string Formatted HTML
182 */
183 public static function dateMenu( $year, $month ) {
184 # Offset overrides year/month selection
185 if( $month && $month !== -1 ) {
186 $encMonth = intval( $month );
187 } else {
188 $encMonth = '';
189 }
190 if( $year ) {
191 $encYear = intval( $year );
192 } elseif( $encMonth ) {
193 $thisMonth = intval( gmdate( 'n' ) );
194 $thisYear = intval( gmdate( 'Y' ) );
195 if( intval($encMonth) > $thisMonth ) {
196 $thisYear--;
197 }
198 $encYear = $thisYear;
199 } else {
200 $encYear = '';
201 }
202 $inputAttribs = array( 'id' => 'year', 'maxlength' => 4, 'size' => 7 );
203 return self::label( wfMessage( 'year' )->text(), 'year' ) . ' '.
204 Html::input( 'year', $encYear, 'number', $inputAttribs ) . ' '.
205 self::label( wfMessage( 'month' )->text(), 'month' ) . ' '.
206 self::monthSelector( $encMonth, -1 );
207 }
208
209 /**
210 * Construct a language selector appropriate for use in a form or preferences
211 *
212 * @param string $selected The language code of the selected language
213 * @param boolean $customisedOnly If true only languages which have some content are listed
214 * @param string $inLanguage The ISO code of the language to display the select list in (optional)
215 * @param array $overrideAttrs Override the attributes of the select tag (since 1.20)
216 * @param Message|null $msg Label message key (since 1.20)
217 * @return array containing 2 items: label HTML and select list HTML
218 */
219 public static function languageSelector( $selected, $customisedOnly = true, $inLanguage = null, $overrideAttrs = array(), Message $msg = null ) {
220 global $wgLanguageCode;
221
222 $include = $customisedOnly ? 'mwfile' : 'mw';
223 $languages = Language::fetchLanguageNames( $inLanguage, $include );
224
225 // Make sure the site language is in the list;
226 // a custom language code might not have a defined name...
227 if( !array_key_exists( $wgLanguageCode, $languages ) ) {
228 $languages[$wgLanguageCode] = $wgLanguageCode;
229 }
230
231 ksort( $languages );
232
233 /**
234 * If a bogus value is set, default to the content language.
235 * Otherwise, no default is selected and the user ends up
236 * with Afrikaans since it's first in the list.
237 */
238 $selected = isset( $languages[$selected] ) ? $selected : $wgLanguageCode;
239 $options = "\n";
240 foreach( $languages as $code => $name ) {
241 $options .= Xml::option( "$code - $name", $code, ($code == $selected) ) . "\n";
242 }
243
244 $attrs = array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' );
245 $attrs = array_merge( $attrs, $overrideAttrs );
246
247 if( $msg === null ) {
248 $msg = wfMessage( 'yourlanguage' );
249 }
250 return array(
251 Xml::label( $msg->text(), $attrs['id'] ),
252 Xml::tags( 'select', $attrs, $options )
253 );
254
255 }
256
257 /**
258 * Shortcut to make a span element
259 * @param $text String content of the element, will be escaped
260 * @param $class String class name of the span element
261 * @param $attribs array other attributes
262 * @return string
263 */
264 public static function span( $text, $class, $attribs = array() ) {
265 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
266 }
267
268 /**
269 * Shortcut to make a specific element with a class attribute
270 * @param $text string content of the element, will be escaped
271 * @param $class string class name of the span element
272 * @param $tag string element name
273 * @param $attribs array other attributes
274 * @return string
275 */
276 public static function wrapClass( $text, $class, $tag = 'span', $attribs = array() ) {
277 return self::tags( $tag, array( 'class' => $class ) + $attribs, $text );
278 }
279
280 /**
281 * Convenience function to build an HTML text input field
282 * @param $name String value of the name attribute
283 * @param $size int value of the size attribute
284 * @param $value mixed value of the value attribute
285 * @param $attribs array other attributes
286 * @return string HTML
287 */
288 public static function input( $name, $size = false, $value = false, $attribs = array() ) {
289 $attributes = array( 'name' => $name );
290
291 if( $size ) {
292 $attributes['size'] = $size;
293 }
294
295 if( $value !== false ) { // maybe 0
296 $attributes['value'] = $value;
297 }
298
299 return self::element( 'input', $attributes + $attribs );
300 }
301
302 /**
303 * Convenience function to build an HTML password input field
304 * @param $name string value of the name attribute
305 * @param $size int value of the size attribute
306 * @param $value mixed value of the value attribute
307 * @param $attribs array other attributes
308 * @return string HTML
309 */
310 public static function password( $name, $size = false, $value = false, $attribs = array() ) {
311 return self::input( $name, $size, $value, array_merge( $attribs, array( 'type' => 'password' ) ) );
312 }
313
314 /**
315 * Internal function for use in checkboxes and radio buttons and such.
316 *
317 * @param $name string
318 * @param $present bool
319 *
320 * @return array
321 */
322 public static function attrib( $name, $present = true ) {
323 return $present ? array( $name => $name ) : array();
324 }
325
326 /**
327 * Convenience function to build an HTML checkbox
328 * @param $name String value of the name attribute
329 * @param $checked Bool Whether the checkbox is checked or not
330 * @param $attribs Array other attributes
331 * @return string HTML
332 */
333 public static function check( $name, $checked = false, $attribs=array() ) {
334 return self::element( 'input', array_merge(
335 array(
336 'name' => $name,
337 'type' => 'checkbox',
338 'value' => 1 ),
339 self::attrib( 'checked', $checked ),
340 $attribs ) );
341 }
342
343 /**
344 * Convenience function to build an HTML radio button
345 * @param $name String value of the name attribute
346 * @param $value String value of the value attribute
347 * @param $checked Bool Whether the checkbox is checked or not
348 * @param $attribs Array other attributes
349 * @return string HTML
350 */
351 public static function radio( $name, $value, $checked = false, $attribs = array() ) {
352 return self::element( 'input', array(
353 'name' => $name,
354 'type' => 'radio',
355 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
356 }
357
358 /**
359 * Convenience function to build an HTML form label
360 * @param $label String text of the label
361 * @param $id
362 * @param $attribs Array an attribute array. This will usuall be
363 * the same array as is passed to the corresponding input element,
364 * so this function will cherry-pick appropriate attributes to
365 * apply to the label as well; only class and title are applied.
366 * @return string HTML
367 */
368 public static function label( $label, $id, $attribs = array() ) {
369 $a = array( 'for' => $id );
370
371 # FIXME avoid copy pasting below:
372 if( isset( $attribs['class'] ) ){
373 $a['class'] = $attribs['class'];
374 }
375 if( isset( $attribs['title'] ) ){
376 $a['title'] = $attribs['title'];
377 }
378
379 return self::element( 'label', $a, $label );
380 }
381
382 /**
383 * Convenience function to build an HTML text input field with a label
384 * @param $label String text of the label
385 * @param $name String value of the name attribute
386 * @param $id String id of the input
387 * @param $size Int|Bool value of the size attribute
388 * @param $value String|Bool value of the value attribute
389 * @param $attribs array other attributes
390 * @return string HTML
391 */
392 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs = array() ) {
393 list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
394 return $label . '&#160;' . $input;
395 }
396
397 /**
398 * Same as Xml::inputLabel() but return input and label in an array
399 *
400 * @param $label String
401 * @param $name String
402 * @param $id String
403 * @param $size Int|Bool
404 * @param $value String|Bool
405 * @param $attribs array
406 *
407 * @return array
408 */
409 public static function inputLabelSep( $label, $name, $id, $size = false, $value = false, $attribs = array() ) {
410 return array(
411 Xml::label( $label, $id, $attribs ),
412 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
413 );
414 }
415
416 /**
417 * Convenience function to build an HTML checkbox with a label
418 *
419 * @param $label
420 * @param $name
421 * @param $id
422 * @param $checked bool
423 * @param $attribs array
424 *
425 * @return string HTML
426 */
427 public static function checkLabel( $label, $name, $id, $checked = false, $attribs = array() ) {
428 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
429 '&#160;' .
430 self::label( $label, $id, $attribs );
431 }
432
433 /**
434 * Convenience function to build an HTML radio button with a label
435 *
436 * @param $label
437 * @param $name
438 * @param $value
439 * @param $id
440 * @param $checked bool
441 * @param $attribs array
442 *
443 * @return string HTML
444 */
445 public static function radioLabel( $label, $name, $value, $id, $checked = false, $attribs = array() ) {
446 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
447 '&#160;' .
448 self::label( $label, $id, $attribs );
449 }
450
451 /**
452 * Convenience function to build an HTML submit button
453 * @param $value String: label text for the button
454 * @param $attribs Array: optional custom attributes
455 * @return string HTML
456 */
457 public static function submitButton( $value, $attribs = array() ) {
458 return Html::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
459 }
460
461 /**
462 * Convenience function to build an HTML drop-down list item.
463 * @param $text String: text for this item
464 * @param $value String: form submission value; if empty, use text
465 * @param $selected boolean: if true, will be the default selected item
466 * @param $attribs array: optional additional HTML attributes
467 * @return string HTML
468 */
469 public static function option( $text, $value=null, $selected = false,
470 $attribs = array() ) {
471 if( !is_null( $value ) ) {
472 $attribs['value'] = $value;
473 }
474 if( $selected ) {
475 $attribs['selected'] = 'selected';
476 }
477 return Html::element( 'option', $attribs, $text );
478 }
479
480 /**
481 * Build a drop-down box from a textual list.
482 *
483 * @param $name Mixed: Name and id for the drop-down
484 * @param $list Mixed: Correctly formatted text (newline delimited) to be used to generate the options
485 * @param $other Mixed: Text for the "Other reasons" option
486 * @param $selected Mixed: Option which should be pre-selected
487 * @param $class Mixed: CSS classes for the drop-down
488 * @param $tabindex Mixed: Value of the tabindex attribute
489 * @return string
490 */
491 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = null ) {
492 $optgroup = false;
493
494 $options = self::option( $other, 'other', $selected === 'other' );
495
496 foreach ( explode( "\n", $list ) as $option) {
497 $value = trim( $option );
498 if ( $value == '' ) {
499 continue;
500 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
501 // A new group is starting ...
502 $value = trim( substr( $value, 1 ) );
503 if( $optgroup ) $options .= self::closeElement('optgroup');
504 $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
505 $optgroup = true;
506 } elseif ( substr( $value, 0, 2) == '**' ) {
507 // groupmember
508 $value = trim( substr( $value, 2 ) );
509 $options .= self::option( $value, $value, $selected === $value );
510 } else {
511 // groupless reason list
512 if( $optgroup ) $options .= self::closeElement('optgroup');
513 $options .= self::option( $value, $value, $selected === $value );
514 $optgroup = false;
515 }
516 }
517
518 if( $optgroup ) $options .= self::closeElement('optgroup');
519
520 $attribs = array();
521
522 if( $name ) {
523 $attribs['id'] = $name;
524 $attribs['name'] = $name;
525 }
526
527 if( $class ) {
528 $attribs['class'] = $class;
529 }
530
531 if( $tabindex ) {
532 $attribs['tabindex'] = $tabindex;
533 }
534
535 return Xml::openElement( 'select', $attribs )
536 . "\n"
537 . $options
538 . "\n"
539 . Xml::closeElement( 'select' );
540 }
541
542 /**
543 * Shortcut for creating fieldsets.
544 *
545 * @param $legend string|bool Legend of the fieldset. If evaluates to false, legend is not added.
546 * @param $content string Pre-escaped content for the fieldset. If false, only open fieldset is returned.
547 * @param $attribs array Any attributes to fieldset-element.
548 *
549 * @return string
550 */
551 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
552 $s = Xml::openElement( 'fieldset', $attribs ) . "\n";
553
554 if ( $legend ) {
555 $s .= Xml::element( 'legend', null, $legend ) . "\n";
556 }
557
558 if ( $content !== false ) {
559 $s .= $content . "\n";
560 $s .= Xml::closeElement( 'fieldset' ) . "\n";
561 }
562
563 return $s;
564 }
565
566 /**
567 * Shortcut for creating textareas.
568 *
569 * @param $name string The 'name' for the textarea
570 * @param $content string Content for the textarea
571 * @param $cols int The number of columns for the textarea
572 * @param $rows int The number of rows for the textarea
573 * @param $attribs array Any other attributes for the textarea
574 *
575 * @return string
576 */
577 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
578 return self::element( 'textarea',
579 array(
580 'name' => $name,
581 'id' => $name,
582 'cols' => $cols,
583 'rows' => $rows
584 ) + $attribs,
585 $content, false );
586 }
587
588 /**
589 * Returns an escaped string suitable for inclusion in a string literal
590 * for JavaScript source code.
591 * Illegal control characters are assumed not to be present.
592 *
593 * @param $string String to escape
594 * @return String
595 */
596 public static function escapeJsString( $string ) {
597 // See ECMA 262 section 7.8.4 for string literal format
598 $pairs = array(
599 "\\" => "\\\\",
600 "\"" => "\\\"",
601 '\'' => '\\\'',
602 "\n" => "\\n",
603 "\r" => "\\r",
604
605 # To avoid closing the element or CDATA section
606 "<" => "\\x3c",
607 ">" => "\\x3e",
608
609 # To avoid any complaints about bad entity refs
610 "&" => "\\x26",
611
612 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
613 # Encode certain Unicode formatting chars so affected
614 # versions of Gecko don't misinterpret our strings;
615 # this is a common problem with Farsi text.
616 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
617 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
618 );
619
620 return strtr( $string, $pairs );
621 }
622
623 /**
624 * Encode a variable of unknown type to JavaScript.
625 * Arrays are converted to JS arrays, objects are converted to JS associative
626 * arrays (objects). So cast your PHP associative arrays to objects before
627 * passing them to here.
628 *
629 * @param $value
630 *
631 * @return string
632 */
633 public static function encodeJsVar( $value ) {
634 if ( is_bool( $value ) ) {
635 $s = $value ? 'true' : 'false';
636 } elseif ( is_null( $value ) ) {
637 $s = 'null';
638 } elseif ( is_int( $value ) || is_float( $value ) ) {
639 $s = strval($value);
640 } elseif ( is_array( $value ) && // Make sure it's not associative.
641 array_keys($value) === range( 0, count($value) - 1 ) ||
642 count($value) == 0
643 ) {
644 $s = '[';
645 foreach ( $value as $elt ) {
646 if ( $s != '[' ) {
647 $s .= ',';
648 }
649 $s .= self::encodeJsVar( $elt );
650 }
651 $s .= ']';
652 } elseif ( $value instanceof XmlJsCode ) {
653 $s = $value->value;
654 } elseif ( is_object( $value ) || is_array( $value ) ) {
655 // Objects and associative arrays
656 $s = '{';
657 foreach ( (array)$value as $name => $elt ) {
658 if ( $s != '{' ) {
659 $s .= ',';
660 }
661
662 $s .= '"' . self::escapeJsString( $name ) . '":' .
663 self::encodeJsVar( $elt );
664 }
665 $s .= '}';
666 } else {
667 $s = '"' . self::escapeJsString( $value ) . '"';
668 }
669 return $s;
670 }
671
672 /**
673 * Create a call to a JavaScript function. The supplied arguments will be
674 * encoded using Xml::encodeJsVar().
675 *
676 * @param $name String The name of the function to call, or a JavaScript expression
677 * which evaluates to a function object which is called.
678 * @param $args Array of arguments to pass to the function.
679 *
680 * @since 1.17
681 *
682 * @return string
683 */
684 public static function encodeJsCall( $name, $args ) {
685 $s = "$name(";
686 $first = true;
687
688 foreach ( $args as $arg ) {
689 if ( $first ) {
690 $first = false;
691 } else {
692 $s .= ', ';
693 }
694
695 $s .= Xml::encodeJsVar( $arg );
696 }
697
698 $s .= ");\n";
699
700 return $s;
701 }
702
703 /**
704 * Check if a string is well-formed XML.
705 * Must include the surrounding tag.
706 *
707 * @param $text String: string to test.
708 * @return bool
709 *
710 * @todo Error position reporting return
711 */
712 public static function isWellFormed( $text ) {
713 $parser = xml_parser_create( "UTF-8" );
714
715 # case folding violates XML standard, turn it off
716 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
717
718 if( !xml_parse( $parser, $text, true ) ) {
719 //$err = xml_error_string( xml_get_error_code( $parser ) );
720 //$position = xml_get_current_byte_index( $parser );
721 //$fragment = $this->extractFragment( $html, $position );
722 //$this->mXmlError = "$err at byte $position:\n$fragment";
723 xml_parser_free( $parser );
724 return false;
725 }
726
727 xml_parser_free( $parser );
728
729 return true;
730 }
731
732 /**
733 * Check if a string is a well-formed XML fragment.
734 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
735 * and can use HTML named entities.
736 *
737 * @param $text String:
738 * @return bool
739 */
740 public static function isWellFormedXmlFragment( $text ) {
741 $html =
742 Sanitizer::hackDocType() .
743 '<html>' .
744 $text .
745 '</html>';
746
747 return Xml::isWellFormed( $html );
748 }
749
750 /**
751 * Replace " > and < with their respective HTML entities ( &quot;,
752 * &gt;, &lt;)
753 *
754 * @param $in String: text that might contain HTML tags.
755 * @return string Escaped string
756 */
757 public static function escapeTagsOnly( $in ) {
758 return str_replace(
759 array( '"', '>', '<' ),
760 array( '&quot;', '&gt;', '&lt;' ),
761 $in );
762 }
763
764 /**
765 * Generate a form (without the opening form element).
766 * Output optionally includes a submit button.
767 * @param $fields Array Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
768 * @param $submitLabel String A message containing a label for the submit button.
769 * @return string HTML form.
770 */
771 public static function buildForm( $fields, $submitLabel = null ) {
772 $form = '';
773 $form .= "<table><tbody>";
774
775 foreach( $fields as $labelmsg => $input ) {
776 $id = "mw-$labelmsg";
777 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
778 $form .= Xml::tags( 'td', array('class' => 'mw-label'), wfMessage( $labelmsg )->parse() );
779 $form .= Xml::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml::closeElement( 'td' );
780 $form .= Xml::closeElement( 'tr' );
781 }
782
783 if( $submitLabel ) {
784 $form .= Xml::openElement( 'tr' );
785 $form .= Xml::tags( 'td', array(), '' );
786 $form .= Xml::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml::submitButton( wfMessage( $submitLabel )->text() ) . Xml::closeElement( 'td' );
787 $form .= Xml::closeElement( 'tr' );
788 }
789
790 $form .= "</tbody></table>";
791
792 return $form;
793 }
794
795 /**
796 * Build a table of data
797 * @param $rows array An array of arrays of strings, each to be a row in a table
798 * @param $attribs array An array of attributes to apply to the table tag [optional]
799 * @param $headers array An array of strings to use as table headers [optional]
800 * @return string
801 */
802 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
803 $s = Xml::openElement( 'table', $attribs );
804
805 if ( is_array( $headers ) ) {
806 $s .= Xml::openElement( 'thead', $attribs );
807
808 foreach( $headers as $id => $header ) {
809 $attribs = array();
810
811 if ( is_string( $id ) ) {
812 $attribs['id'] = $id;
813 }
814
815 $s .= Xml::element( 'th', $attribs, $header );
816 }
817 $s .= Xml::closeElement( 'thead' );
818 }
819
820 foreach( $rows as $id => $row ) {
821 $attribs = array();
822
823 if ( is_string( $id ) ) {
824 $attribs['id'] = $id;
825 }
826
827 $s .= Xml::buildTableRow( $attribs, $row );
828 }
829
830 $s .= Xml::closeElement( 'table' );
831
832 return $s;
833 }
834
835 /**
836 * Build a row for a table
837 * @param $attribs array An array of attributes to apply to the tr tag
838 * @param $cells array An array of strings to put in <td>
839 * @return string
840 */
841 public static function buildTableRow( $attribs, $cells ) {
842 $s = Xml::openElement( 'tr', $attribs );
843
844 foreach( $cells as $id => $cell ) {
845
846 $attribs = array();
847
848 if ( is_string( $id ) ) {
849 $attribs['id'] = $id;
850 }
851
852 $s .= Xml::element( 'td', $attribs, $cell );
853 }
854
855 $s .= Xml::closeElement( 'tr' );
856
857 return $s;
858 }
859 }
860
861 class XmlSelect {
862 protected $options = array();
863 protected $default = false;
864 protected $attributes = array();
865
866 public function __construct( $name = false, $id = false, $default = false ) {
867 if ( $name ) {
868 $this->setAttribute( 'name', $name );
869 }
870
871 if ( $id ) {
872 $this->setAttribute( 'id', $id );
873 }
874
875 if ( $default !== false ) {
876 $this->default = $default;
877 }
878 }
879
880 /**
881 * @param $default
882 */
883 public function setDefault( $default ) {
884 $this->default = $default;
885 }
886
887 /**
888 * @param $name string
889 * @param $value
890 */
891 public function setAttribute( $name, $value ) {
892 $this->attributes[$name] = $value;
893 }
894
895 /**
896 * @param $name
897 * @return array|null
898 */
899 public function getAttribute( $name ) {
900 if ( isset( $this->attributes[$name] ) ) {
901 return $this->attributes[$name];
902 } else {
903 return null;
904 }
905 }
906
907 /**
908 * @param $name
909 * @param $value bool
910 */
911 public function addOption( $name, $value = false ) {
912 // Stab stab stab
913 $value = ($value !== false) ? $value : $name;
914
915 $this->options[] = array( $name => $value );
916 }
917
918 /**
919 * This accepts an array of form
920 * label => value
921 * label => ( label => value, label => value )
922 *
923 * @param $options
924 */
925 public function addOptions( $options ) {
926 $this->options[] = $options;
927 }
928
929 /**
930 * This accepts an array of form
931 * label => value
932 * label => ( label => value, label => value )
933 *
934 * @param $options
935 * @param bool $default
936 * @return string
937 */
938 static function formatOptions( $options, $default = false ) {
939 $data = '';
940
941 foreach( $options as $label => $value ) {
942 if ( is_array( $value ) ) {
943 $contents = self::formatOptions( $value, $default );
944 $data .= Html::rawElement( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
945 } else {
946 $data .= Xml::option( $label, $value, $value === $default ) . "\n";
947 }
948 }
949
950 return $data;
951 }
952
953 /**
954 * @return string
955 */
956 public function getHTML() {
957 $contents = '';
958
959 foreach ( $this->options as $options ) {
960 $contents .= self::formatOptions( $options, $this->default );
961 }
962
963 return Html::rawElement( 'select', $this->attributes, rtrim( $contents ) );
964 }
965 }
966
967 /**
968 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
969 * interpret a given string as being a JavaScript expression, instead of string
970 * data.
971 *
972 * Example:
973 *
974 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
975 *
976 * Returns "a + b".
977 * @since 1.17
978 */
979 class XmlJsCode {
980 public $value;
981
982 function __construct( $value ) {
983 $this->value = $value;
984 }
985 }