(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( 'name' => $name,
580 'id' => $name,
581 'cols' => $cols,
582 'rows' => $rows
583 ) + $attribs,
584 $content, false );
585 }
586
587 /**
588 * Returns an escaped string suitable for inclusion in a string literal
589 * for JavaScript source code.
590 * Illegal control characters are assumed not to be present.
591 *
592 * @param $string String to escape
593 * @return String
594 */
595 public static function escapeJsString( $string ) {
596 // See ECMA 262 section 7.8.4 for string literal format
597 $pairs = array(
598 "\\" => "\\\\",
599 "\"" => "\\\"",
600 '\'' => '\\\'',
601 "\n" => "\\n",
602 "\r" => "\\r",
603
604 # To avoid closing the element or CDATA section
605 "<" => "\\x3c",
606 ">" => "\\x3e",
607
608 # To avoid any complaints about bad entity refs
609 "&" => "\\x26",
610
611 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
612 # Encode certain Unicode formatting chars so affected
613 # versions of Gecko don't misinterpret our strings;
614 # this is a common problem with Farsi text.
615 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
616 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
617 );
618
619 return strtr( $string, $pairs );
620 }
621
622 /**
623 * Encode a variable of unknown type to JavaScript.
624 * Arrays are converted to JS arrays, objects are converted to JS associative
625 * arrays (objects). So cast your PHP associative arrays to objects before
626 * passing them to here.
627 *
628 * @param $value
629 *
630 * @return string
631 */
632 public static function encodeJsVar( $value ) {
633 if ( is_bool( $value ) ) {
634 $s = $value ? 'true' : 'false';
635 } elseif ( is_null( $value ) ) {
636 $s = 'null';
637 } elseif ( is_int( $value ) || is_float( $value ) ) {
638 $s = strval($value);
639 } elseif ( is_array( $value ) && // Make sure it's not associative.
640 array_keys($value) === range( 0, count($value) - 1 ) ||
641 count($value) == 0
642 ) {
643 $s = '[';
644 foreach ( $value as $elt ) {
645 if ( $s != '[' ) {
646 $s .= ',';
647 }
648 $s .= self::encodeJsVar( $elt );
649 }
650 $s .= ']';
651 } elseif ( $value instanceof XmlJsCode ) {
652 $s = $value->value;
653 } elseif ( is_object( $value ) || is_array( $value ) ) {
654 // Objects and associative arrays
655 $s = '{';
656 foreach ( (array)$value as $name => $elt ) {
657 if ( $s != '{' ) {
658 $s .= ',';
659 }
660
661 $s .= '"' . self::escapeJsString( $name ) . '":' .
662 self::encodeJsVar( $elt );
663 }
664 $s .= '}';
665 } else {
666 $s = '"' . self::escapeJsString( $value ) . '"';
667 }
668 return $s;
669 }
670
671 /**
672 * Create a call to a JavaScript function. The supplied arguments will be
673 * encoded using Xml::encodeJsVar().
674 *
675 * @param $name String The name of the function to call, or a JavaScript expression
676 * which evaluates to a function object which is called.
677 * @param $args Array of arguments to pass to the function.
678 *
679 * @since 1.17
680 *
681 * @return string
682 */
683 public static function encodeJsCall( $name, $args ) {
684 $s = "$name(";
685 $first = true;
686
687 foreach ( $args as $arg ) {
688 if ( $first ) {
689 $first = false;
690 } else {
691 $s .= ', ';
692 }
693
694 $s .= Xml::encodeJsVar( $arg );
695 }
696
697 $s .= ");\n";
698
699 return $s;
700 }
701
702 /**
703 * Check if a string is well-formed XML.
704 * Must include the surrounding tag.
705 *
706 * @param $text String: string to test.
707 * @return bool
708 *
709 * @todo Error position reporting return
710 */
711 public static function isWellFormed( $text ) {
712 $parser = xml_parser_create( "UTF-8" );
713
714 # case folding violates XML standard, turn it off
715 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
716
717 if( !xml_parse( $parser, $text, true ) ) {
718 //$err = xml_error_string( xml_get_error_code( $parser ) );
719 //$position = xml_get_current_byte_index( $parser );
720 //$fragment = $this->extractFragment( $html, $position );
721 //$this->mXmlError = "$err at byte $position:\n$fragment";
722 xml_parser_free( $parser );
723 return false;
724 }
725
726 xml_parser_free( $parser );
727
728 return true;
729 }
730
731 /**
732 * Check if a string is a well-formed XML fragment.
733 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
734 * and can use HTML named entities.
735 *
736 * @param $text String:
737 * @return bool
738 */
739 public static function isWellFormedXmlFragment( $text ) {
740 $html =
741 Sanitizer::hackDocType() .
742 '<html>' .
743 $text .
744 '</html>';
745
746 return Xml::isWellFormed( $html );
747 }
748
749 /**
750 * Replace " > and < with their respective HTML entities ( &quot;,
751 * &gt;, &lt;)
752 *
753 * @param $in String: text that might contain HTML tags.
754 * @return string Escaped string
755 */
756 public static function escapeTagsOnly( $in ) {
757 return str_replace(
758 array( '"', '>', '<' ),
759 array( '&quot;', '&gt;', '&lt;' ),
760 $in );
761 }
762
763 /**
764 * Generate a form (without the opening form element).
765 * Output optionally includes a submit button.
766 * @param $fields Array Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
767 * @param $submitLabel String A message containing a label for the submit button.
768 * @return string HTML form.
769 */
770 public static function buildForm( $fields, $submitLabel = null ) {
771 $form = '';
772 $form .= "<table><tbody>";
773
774 foreach( $fields as $labelmsg => $input ) {
775 $id = "mw-$labelmsg";
776 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
777 $form .= Xml::tags( 'td', array('class' => 'mw-label'), wfMessage( $labelmsg )->parse() );
778 $form .= Xml::openElement( 'td', array( 'class' => 'mw-input' ) ) . $input . Xml::closeElement( 'td' );
779 $form .= Xml::closeElement( 'tr' );
780 }
781
782 if( $submitLabel ) {
783 $form .= Xml::openElement( 'tr' );
784 $form .= Xml::tags( 'td', array(), '' );
785 $form .= Xml::openElement( 'td', array( 'class' => 'mw-submit' ) ) . Xml::submitButton( wfMessage( $submitLabel )->text() ) . Xml::closeElement( 'td' );
786 $form .= Xml::closeElement( 'tr' );
787 }
788
789 $form .= "</tbody></table>";
790
791 return $form;
792 }
793
794 /**
795 * Build a table of data
796 * @param $rows array An array of arrays of strings, each to be a row in a table
797 * @param $attribs array An array of attributes to apply to the table tag [optional]
798 * @param $headers array An array of strings to use as table headers [optional]
799 * @return string
800 */
801 public static function buildTable( $rows, $attribs = array(), $headers = null ) {
802 $s = Xml::openElement( 'table', $attribs );
803
804 if ( is_array( $headers ) ) {
805 $s .= Xml::openElement( 'thead', $attribs );
806
807 foreach( $headers as $id => $header ) {
808 $attribs = array();
809
810 if ( is_string( $id ) ) {
811 $attribs['id'] = $id;
812 }
813
814 $s .= Xml::element( 'th', $attribs, $header );
815 }
816 $s .= Xml::closeElement( 'thead' );
817 }
818
819 foreach( $rows as $id => $row ) {
820 $attribs = array();
821
822 if ( is_string( $id ) ) {
823 $attribs['id'] = $id;
824 }
825
826 $s .= Xml::buildTableRow( $attribs, $row );
827 }
828
829 $s .= Xml::closeElement( 'table' );
830
831 return $s;
832 }
833
834 /**
835 * Build a row for a table
836 * @param $attribs array An array of attributes to apply to the tr tag
837 * @param $cells array An array of strings to put in <td>
838 * @return string
839 */
840 public static function buildTableRow( $attribs, $cells ) {
841 $s = Xml::openElement( 'tr', $attribs );
842
843 foreach( $cells as $id => $cell ) {
844
845 $attribs = array();
846
847 if ( is_string( $id ) ) {
848 $attribs['id'] = $id;
849 }
850
851 $s .= Xml::element( 'td', $attribs, $cell );
852 }
853
854 $s .= Xml::closeElement( 'tr' );
855
856 return $s;
857 }
858 }
859
860 class XmlSelect {
861 protected $options = array();
862 protected $default = false;
863 protected $attributes = array();
864
865 public function __construct( $name = false, $id = false, $default = false ) {
866 if ( $name ) {
867 $this->setAttribute( 'name', $name );
868 }
869
870 if ( $id ) {
871 $this->setAttribute( 'id', $id );
872 }
873
874 if ( $default !== false ) {
875 $this->default = $default;
876 }
877 }
878
879 /**
880 * @param $default
881 */
882 public function setDefault( $default ) {
883 $this->default = $default;
884 }
885
886 /**
887 * @param $name string
888 * @param $value
889 */
890 public function setAttribute( $name, $value ) {
891 $this->attributes[$name] = $value;
892 }
893
894 /**
895 * @param $name
896 * @return array|null
897 */
898 public function getAttribute( $name ) {
899 if ( isset( $this->attributes[$name] ) ) {
900 return $this->attributes[$name];
901 } else {
902 return null;
903 }
904 }
905
906 /**
907 * @param $name
908 * @param $value bool
909 */
910 public function addOption( $name, $value = false ) {
911 // Stab stab stab
912 $value = ($value !== false) ? $value : $name;
913
914 $this->options[] = array( $name => $value );
915 }
916
917 /**
918 * This accepts an array of form
919 * label => value
920 * label => ( label => value, label => value )
921 *
922 * @param $options
923 */
924 public function addOptions( $options ) {
925 $this->options[] = $options;
926 }
927
928 /**
929 * This accepts an array of form
930 * label => value
931 * label => ( label => value, label => value )
932 *
933 * @param $options
934 * @param bool $default
935 * @return string
936 */
937 static function formatOptions( $options, $default = false ) {
938 $data = '';
939
940 foreach( $options as $label => $value ) {
941 if ( is_array( $value ) ) {
942 $contents = self::formatOptions( $value, $default );
943 $data .= Html::rawElement( 'optgroup', array( 'label' => $label ), $contents ) . "\n";
944 } else {
945 $data .= Xml::option( $label, $value, $value === $default ) . "\n";
946 }
947 }
948
949 return $data;
950 }
951
952 /**
953 * @return string
954 */
955 public function getHTML() {
956 $contents = '';
957
958 foreach ( $this->options as $options ) {
959 $contents .= self::formatOptions( $options, $this->default );
960 }
961
962 return Html::rawElement( 'select', $this->attributes, rtrim( $contents ) );
963 }
964 }
965
966 /**
967 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
968 * interpret a given string as being a JavaScript expression, instead of string
969 * data.
970 *
971 * Example:
972 *
973 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
974 *
975 * Returns "a + b".
976 * @since 1.17
977 */
978 class XmlJsCode {
979 public $value;
980
981 function __construct( $value ) {
982 $this->value = $value;
983 }
984 }