* Output title before class in Linker::link() to match behavior of makeLink() and...
[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 private 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 return $out;
52 } else {
53 throw new MWException( 'Expected attribute array, got something else in ' . __METHOD__ );
54 }
55 }
56
57 /**
58 * Given a string of attributes for an element, return an array of key =>
59 * value pairs. Can be used for backward compatibility with old functions
60 * that accept attributes as strings instead of arrays. Does not validate
61 * the string, so watch out for GIGO.
62 *
63 * @param $attribs string
64 * @return array
65 */
66 public static function explodeAttributes( $attribs ) {
67 $matches = array();
68 preg_match_all( '/([^\s=\'"]+)\s*=\s*(?:\'([^\']*)\'|"([^"]*)")/',
69 $attribs, $matches );
70 $ret = array();
71 for( $i = 0; $i < count( $matches[0] ); ++$i ) {
72 if( $matches[2][$i] !== '' ) {
73 $val = $matches[2][$i];
74 } else {
75 $val = $matches[3][$i];
76 }
77 $ret[$matches[1][$i]] = html_entity_decode( $val );
78 }
79 return $ret;
80 }
81
82 /**
83 * Format an XML element as with self::element(), but run text through the
84 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
85 * is passed.
86 *
87 * @param $element String:
88 * @param $attribs Array: Name=>value pairs. Values will be escaped.
89 * @param $contents String: NULL to make an open tag only; '' for a contentless closed tag (default)
90 * @return string
91 */
92 public static function elementClean( $element, $attribs = array(), $contents = '') {
93 if( $attribs ) {
94 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
95 }
96 if( $contents ) {
97 wfProfileIn( __METHOD__ . '-norm' );
98 $contents = UtfNormal::cleanUp( $contents );
99 wfProfileOut( __METHOD__ . '-norm' );
100 }
101 return self::element( $element, $attribs, $contents );
102 }
103
104 /**
105 * This opens an XML element
106 *
107 * @param $element name of the element
108 * @param $attribs array of attributes, see Xml::expandAttributes()
109 * @return string
110 */
111 public static function openElement( $element, $attribs = null ) {
112 return '<' . $element . self::expandAttributes( $attribs ) . '>';
113 }
114
115 /**
116 * Shortcut to close an XML element
117 * @param $element element name
118 * @return string
119 */
120 public static function closeElement( $element ) { return "</$element>"; }
121
122 /**
123 * Same as Xml::element(), but does not escape contents. Handy when the
124 * content you have is already valid xml.
125 *
126 * @param $element element name
127 * @param $attribs array of attributes
128 * @param $contents content of the element
129 * @return string
130 */
131 public static function tags( $element, $attribs = null, $contents ) {
132 return self::openElement( $element, $attribs ) . $contents . "</$element>";
133 }
134
135 /**
136 * Build a drop-down box for selecting a namespace
137 *
138 * @param $selected Mixed: Namespace which should be pre-selected
139 * @param $all Mixed: Value of an item denoting all namespaces, or null to omit
140 * @param $hidden Mixed: Include hidden namespaces? [WTF? --RC]
141 * @param $element_name String: value of the "name" attribute of the select tag
142 * @return string
143 */
144 public static function namespaceSelector( $selected = '', $all = null, $hidden = false, $element_name = 'namespace' ) {
145 global $wgContLang;
146 $namespaces = $wgContLang->getFormattedNamespaces();
147 $options = array();
148
149 // Godawful hack... we'll be frequently passed selected namespaces
150 // as strings since PHP is such a shithole.
151 // But we also don't want blanks and nulls and "all"s matching 0,
152 // so let's convert *just* string ints to clean ints.
153 if( preg_match( '/^\d+$/', $selected ) ) {
154 $selected = intval( $selected );
155 }
156
157 if( !is_null( $all ) )
158 $namespaces = array( $all => wfMsg( 'namespacesall' ) ) + $namespaces;
159 foreach( $namespaces as $index => $name ) {
160 if( $index < NS_MAIN )
161 continue;
162 if( $index === 0 )
163 $name = wfMsg( 'blanknamespace' );
164 $options[] = self::option( $name, $index, $index === $selected );
165 }
166
167 return Xml::openElement( 'select', array( 'id' => 'namespace', 'name' => $element_name,
168 'class' => 'namespaceselector' ) )
169 . "\n"
170 . implode( "\n", $options )
171 . "\n"
172 . Xml::closeElement( 'select' );
173 }
174
175 /**
176 * Create a date selector
177 *
178 * @param $selected Mixed: the month which should be selected, default ''
179 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
180 * @param $id String: Element identifier
181 * @return String: Html string containing the month selector
182 */
183 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
184 global $wgLang;
185 $options = array();
186 if( is_null( $selected ) )
187 $selected = '';
188 if( !is_null( $allmonths ) )
189 $options[] = self::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
190 for( $i = 1; $i < 13; $i++ )
191 $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
192 return self::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
193 . implode( "\n", $options )
194 . self::closeElement( 'select' );
195 }
196
197 /**
198 *
199 * @param $selected The language code of the selected language
200 * @param $customisedOnly If true only languages which have some content are listed
201 * @return array of label and select
202 */
203 public static function languageSelector( $selected, $customisedOnly = true ) {
204 global $wgContLanguageCode;
205 /**
206 * Make sure the site language is in the list; a custom language code
207 * might not have a defined name...
208 */
209 $languages = Language::getLanguageNames( $customisedOnly );
210 if( !array_key_exists( $wgContLanguageCode, $languages ) ) {
211 $languages[$wgContLanguageCode] = $wgContLanguageCode;
212 }
213 ksort( $languages );
214
215 /**
216 * If a bogus value is set, default to the content language.
217 * Otherwise, no default is selected and the user ends up
218 * with an Afrikaans interface since it's first in the list.
219 */
220 $selected = isset( $languages[$selected] ) ? $selected : $wgContLanguageCode;
221 $options = "\n";
222 foreach( $languages as $code => $name ) {
223 $options .= Xml::option( "$code - $name", $code, ($code == $selected) ) . "\n";
224 }
225
226 return array(
227 Xml::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
228 Xml::tags( 'select',
229 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
230 $options
231 )
232 );
233
234 }
235
236 /**
237 * Shortcut to make a span element
238 * @param $text content of the element, will be escaped
239 * @param $class class name of the span element
240 * @param $attribs other attributes
241 * @return string
242 */
243 public static function span( $text, $class, $attribs=array() ) {
244 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
245 }
246
247 /**
248 * Shortcut to make a specific element with a class attribute
249 * @param $text content of the element, will be escaped
250 * @param $class class name of the span element
251 * @param $tag element name
252 * @param $attribs other attributes
253 * @return string
254 */
255 public static function wrapClass( $text, $class, $tag='span', $attribs=array() ) {
256 return self::tags( $tag, array( 'class' => $class ) + $attribs, $text );
257 }
258
259 /**
260 * Convenience function to build an HTML text input field
261 * @param $name value of the name attribute
262 * @param $size value of the size attribute
263 * @param $value value of the value attribute
264 * @param $attribs other attributes
265 * @return string HTML
266 */
267 public static function input( $name, $size=false, $value=false, $attribs=array() ) {
268 return self::element( 'input', array(
269 'name' => $name,
270 'size' => $size,
271 'value' => $value ) + $attribs );
272 }
273
274 /**
275 * Convenience function to build an HTML password input field
276 * @param $name value of the name attribute
277 * @param $size value of the size attribute
278 * @param $value value of the value attribute
279 * @param $attribs other attributes
280 * @return string HTML
281 */
282 public static function password( $name, $size=false, $value=false, $attribs=array() ) {
283 return self::input( $name, $size, $value, array_merge($attribs, array('type' => 'password')));
284 }
285
286 /**
287 * Internal function for use in checkboxes and radio buttons and such.
288 * @return array
289 */
290 public static function attrib( $name, $present = true ) {
291 return $present ? array( $name => $name ) : array();
292 }
293
294 /**
295 * Convenience function to build an HTML checkbox
296 * @param $name value of the name attribute
297 * @param $checked Whether the checkbox is checked or not
298 * @param $attribs other attributes
299 * @return string HTML
300 */
301 public static function check( $name, $checked=false, $attribs=array() ) {
302 return self::element( 'input', array_merge(
303 array(
304 'name' => $name,
305 'type' => 'checkbox',
306 'value' => 1 ),
307 self::attrib( 'checked', $checked ),
308 $attribs ) );
309 }
310
311 /**
312 * Convenience function to build an HTML radio button
313 * @param $name value of the name attribute
314 * @param $value value of the value attribute
315 * @param $checked Whether the checkbox is checked or not
316 * @param $attribs other attributes
317 * @return string HTML
318 */
319 public static function radio( $name, $value, $checked=false, $attribs=array() ) {
320 return self::element( 'input', array(
321 'name' => $name,
322 'type' => 'radio',
323 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
324 }
325
326 /**
327 * Convenience function to build an HTML form label
328 * @param $label text of the label
329 * @param $id
330 * @return string HTML
331 */
332 public static function label( $label, $id ) {
333 return self::element( 'label', array( 'for' => $id ), $label );
334 }
335
336 /**
337 * Convenience function to build an HTML text input field with a label
338 * @param $label text of the label
339 * @param $name value of the name attribute
340 * @param $id id of the input
341 * @param $size value of the size attribute
342 * @param $value value of the value attribute
343 * @param $attribs other attributes
344 * @return string HTML
345 */
346 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
347 list( $label, $input ) = self::inputLabelSep( $label, $name, $id, $size, $value, $attribs );
348 return $label . '&nbsp;' . $input;
349 }
350
351 /**
352 * Same as Xml::inputLabel() but return input and label in an array
353 */
354 public static function inputLabelSep( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
355 return array(
356 Xml::label( $label, $id ),
357 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs )
358 );
359 }
360
361 /**
362 * Convenience function to build an HTML checkbox with a label
363 * @return string HTML
364 */
365 public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
366 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
367 '&nbsp;' .
368 self::label( $label, $id );
369 }
370
371 /**
372 * Convenience function to build an HTML radio button with a label
373 * @return string HTML
374 */
375 public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
376 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
377 '&nbsp;' .
378 self::label( $label, $id );
379 }
380
381 /**
382 * Convenience function to build an HTML submit button
383 * @param $value String: label text for the button
384 * @param $attribs Array: optional custom attributes
385 * @return string HTML
386 */
387 public static function submitButton( $value, $attribs=array() ) {
388 return self::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
389 }
390
391 /**
392 * Convenience function to build an HTML hidden form field.
393 * @param $name String: name attribute for the field
394 * @param $value String: value for the hidden field
395 * @param $attribs Array: optional custom attributes
396 * @return string HTML
397 */
398 public static function hidden( $name, $value, $attribs=array() ) {
399 return self::element( 'input', array(
400 'name' => $name,
401 'type' => 'hidden',
402 'value' => $value ) + $attribs );
403 }
404
405 /**
406 * Convenience function to build an HTML drop-down list item.
407 * @param $text String: text for this item
408 * @param $value String: form submission value; if empty, use text
409 * @param $selected boolean: if true, will be the default selected item
410 * @param $attribs array: optional additional HTML attributes
411 * @return string HTML
412 */
413 public static function option( $text, $value=null, $selected=false,
414 $attribs=array() ) {
415 if( !is_null( $value ) ) {
416 $attribs['value'] = $value;
417 }
418 if( $selected ) {
419 $attribs['selected'] = 'selected';
420 }
421 return self::element( 'option', $attribs, $text );
422 }
423
424 /**
425 * Build a drop-down box from a textual list.
426 *
427 * @param $name Mixed: Name and id for the drop-down
428 * @param $class Mixed: CSS classes for the drop-down
429 * @param $other Mixed: Text for the "Other reasons" option
430 * @param $list Mixed: Correctly formatted text to be used to generate the options
431 * @param $selected Mixed: Option which should be pre-selected
432 * @param $tabindex Mixed: Value of the tabindex attribute
433 * @return string
434 */
435 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = Null ) {
436 $options = '';
437 $optgroup = false;
438
439 $options = self::option( $other, 'other', $selected === 'other' );
440
441 foreach ( explode( "\n", $list ) as $option) {
442 $value = trim( $option );
443 if ( $value == '' ) {
444 continue;
445 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
446 // A new group is starting ...
447 $value = trim( substr( $value, 1 ) );
448 if( $optgroup ) $options .= self::closeElement('optgroup');
449 $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
450 $optgroup = true;
451 } elseif ( substr( $value, 0, 2) == '**' ) {
452 // groupmember
453 $value = trim( substr( $value, 2 ) );
454 $options .= self::option( $value, $value, $selected === $value );
455 } else {
456 // groupless reason list
457 if( $optgroup ) $options .= self::closeElement('optgroup');
458 $options .= self::option( $value, $value, $selected === $value );
459 $optgroup = false;
460 }
461 }
462 if( $optgroup ) $options .= self::closeElement('optgroup');
463
464 $attribs = array();
465 if( $name ) {
466 $attribs['id'] = $name;
467 $attribs['name'] = $name;
468 }
469 if( $class ) {
470 $attribs['class'] = $class;
471 }
472 if( $tabindex ) {
473 $attribs['tabindex'] = $tabindex;
474 }
475 return Xml::openElement( 'select', $attribs )
476 . "\n"
477 . $options
478 . "\n"
479 . Xml::closeElement( 'select' );
480 }
481
482 /**
483 * Shortcut for creating fieldsets.
484 *
485 * @param $legend Legend of the fieldset. If evaluates to false, legend is not added.
486 * @param $content Pre-escaped content for the fieldset. If false, only open fieldset is returned.
487 * @param $attribs Any attributes to fieldset-element.
488 */
489 public static function fieldset( $legend = false, $content = false, $attribs = array() ) {
490 $s = Xml::openElement( 'fieldset', $attribs ) . "\n";
491 if ( $legend ) {
492 $s .= Xml::element( 'legend', null, $legend ) . "\n";
493 }
494 if ( $content !== false ) {
495 $s .= $content . "\n";
496 $s .= Xml::closeElement( 'fieldset' ) . "\n";
497 }
498
499 return $s;
500 }
501
502 /**
503 * Shortcut for creating textareas.
504 *
505 * @param $name The 'name' for the textarea
506 * @param $content Content for the textarea
507 * @param $cols The number of columns for the textarea
508 * @param $rows The number of rows for the textarea
509 * @param $attribs Any other attributes for the textarea
510 */
511 public static function textarea( $name, $content, $cols = 40, $rows = 5, $attribs = array() ) {
512 return self::element( 'textarea',
513 array( 'name' => $name,
514 'id' => $name,
515 'cols' => $cols,
516 'rows' => $rows
517 ) + $attribs,
518 $content, false );
519 }
520
521 /**
522 * Returns an escaped string suitable for inclusion in a string literal
523 * for JavaScript source code.
524 * Illegal control characters are assumed not to be present.
525 *
526 * @param $string String to escape
527 * @return String
528 */
529 public static function escapeJsString( $string ) {
530 // See ECMA 262 section 7.8.4 for string literal format
531 $pairs = array(
532 "\\" => "\\\\",
533 "\"" => "\\\"",
534 '\'' => '\\\'',
535 "\n" => "\\n",
536 "\r" => "\\r",
537
538 # To avoid closing the element or CDATA section
539 "<" => "\\x3c",
540 ">" => "\\x3e",
541
542 # To avoid any complaints about bad entity refs
543 "&" => "\\x26",
544
545 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
546 # Encode certain Unicode formatting chars so affected
547 # versions of Gecko don't misinterpret our strings;
548 # this is a common problem with Farsi text.
549 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
550 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
551 );
552 return strtr( $string, $pairs );
553 }
554
555 /**
556 * Encode a variable of unknown type to JavaScript.
557 * Arrays are converted to JS arrays, objects are converted to JS associative
558 * arrays (objects). So cast your PHP associative arrays to objects before
559 * passing them to here.
560 */
561 public static function encodeJsVar( $value ) {
562 if ( is_bool( $value ) ) {
563 $s = $value ? 'true' : 'false';
564 } elseif ( is_null( $value ) ) {
565 $s = 'null';
566 } elseif ( is_int( $value ) ) {
567 $s = $value;
568 } elseif ( is_array( $value ) ) {
569 $s = '[';
570 foreach ( $value as $elt ) {
571 if ( $s != '[' ) {
572 $s .= ', ';
573 }
574 $s .= self::encodeJsVar( $elt );
575 }
576 $s .= ']';
577 } elseif ( is_object( $value ) ) {
578 $s = '{';
579 foreach ( (array)$value as $name => $elt ) {
580 if ( $s != '{' ) {
581 $s .= ', ';
582 }
583 $s .= '"' . self::escapeJsString( $name ) . '": ' .
584 self::encodeJsVar( $elt );
585 }
586 $s .= '}';
587 } else {
588 $s = '"' . self::escapeJsString( $value ) . '"';
589 }
590 return $s;
591 }
592
593
594 /**
595 * Check if a string is well-formed XML.
596 * Must include the surrounding tag.
597 *
598 * @param $text String: string to test.
599 * @return bool
600 *
601 * @todo Error position reporting return
602 */
603 public static function isWellFormed( $text ) {
604 $parser = xml_parser_create( "UTF-8" );
605
606 # case folding violates XML standard, turn it off
607 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
608
609 if( !xml_parse( $parser, $text, true ) ) {
610 //$err = xml_error_string( xml_get_error_code( $parser ) );
611 //$position = xml_get_current_byte_index( $parser );
612 //$fragment = $this->extractFragment( $html, $position );
613 //$this->mXmlError = "$err at byte $position:\n$fragment";
614 xml_parser_free( $parser );
615 return false;
616 }
617 xml_parser_free( $parser );
618 return true;
619 }
620
621 /**
622 * Check if a string is a well-formed XML fragment.
623 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
624 * and can use HTML named entities.
625 *
626 * @param $text String:
627 * @return bool
628 */
629 public static function isWellFormedXmlFragment( $text ) {
630 $html =
631 Sanitizer::hackDocType() .
632 '<html>' .
633 $text .
634 '</html>';
635 return Xml::isWellFormed( $html );
636 }
637
638 /**
639 * Replace " > and < with their respective HTML entities ( &quot;,
640 * &gt;, &lt;)
641 *
642 * @param $in String: text that might contain HTML tags.
643 * @return string Escaped string
644 */
645 public static function escapeTagsOnly( $in ) {
646 return str_replace(
647 array( '"', '>', '<' ),
648 array( '&quot;', '&gt;', '&lt;' ),
649 $in );
650 }
651
652 /**
653 * Generate a form (without the opening form element).
654 * Output optionally includes a submit button.
655 * @param $fields Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
656 * @param $submitLabel A message containing a label for the submit button.
657 * @return string HTML form.
658 */
659 public static function buildForm( $fields, $submitLabel = null ) {
660 $form = '';
661 $form .= "<table><tbody>";
662
663 foreach( $fields as $labelmsg => $input ) {
664 $id = "mw-$labelmsg";
665
666 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
667 $form .= Xml::tags( 'td', array('class' => 'mw-label'), wfMsgExt( $labelmsg, array('parseinline') ) );
668 $form .= Xml::openElement( 'td' ) . $input . Xml::closeElement( 'td' );
669 $form .= Xml::closeElement( 'tr' );
670 }
671
672 $form .= "</tbody></table>";
673
674 if ($submitLabel) {
675 $form .= Xml::submitButton( wfMsg($submitLabel) );
676 }
677
678 return $form;
679 }
680 }
681
682 class XmlSelect {
683 protected $options = array();
684 protected $default = false;
685 protected $attributes = array();
686
687 public function __construct( $name = false, $id = false, $default = false ) {
688 if ( $name ) $this->setAttribute( 'name', $name );
689 if ( $id ) $this->setAttribute( 'id', $id );
690 if ( $default ) $this->default = $default;
691 }
692
693 public function setDefault( $default ) {
694 $this->default = $default;
695 }
696
697 public function setAttribute( $name, $value ) {
698 $this->attributes[$name] = $value;
699 }
700
701 public function addOption( $name, $value = false ) {
702 $value = $value ? $value : $name;
703 $this->options[] = Xml::option( $name, $value, $value === $this->default );
704 }
705
706 public function getHTML() {
707 return Xml::tags( 'select', $this->attributes, implode( "\n", $this->options ) );
708 }
709
710 }