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