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