bug fixes:
[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:
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 /** This open an XML element */
79 public static function openElement( $element, $attribs = null ) {
80 return '<' . $element . self::expandAttributes( $attribs ) . '>';
81 }
82
83 // Shortcut
84 public static function closeElement( $element ) { return "</$element>"; }
85
86 /**
87 * Same as <link>element</link>, but does not escape contents. Handy when the
88 * content you have is already valid xml.
89 */
90 public static function tags( $element, $attribs = null, $contents ) {
91 return self::openElement( $element, $attribs ) . $contents . "</$element>";
92 }
93
94 /**
95 * Build a drop-down box for selecting a namespace
96 *
97 * @param mixed $selected Namespace which should be pre-selected
98 * @param mixed $all Value of an item denoting all namespaces, or null to omit
99 * @param bool $hidden Include hidden namespaces? [WTF? --RC]
100 * @return string
101 */
102 public static function namespaceSelector( $selected = '', $all = null, $hidden = false, $element_name = 'namespace' ) {
103 global $wgContLang;
104 $namespaces = $wgContLang->getFormattedNamespaces();
105 $options = array();
106
107 // Godawful hack... we'll be frequently passed selected namespaces
108 // as strings since PHP is such a shithole.
109 // But we also don't want blanks and nulls and "all"s matching 0,
110 // so let's convert *just* string ints to clean ints.
111 if( preg_match( '/^\d+$/', $selected ) ) {
112 $selected = intval( $selected );
113 }
114
115 if( !is_null( $all ) )
116 $namespaces = array( $all => wfMsg( 'namespacesall' ) ) + $namespaces;
117 foreach( $namespaces as $index => $name ) {
118 if( $index < NS_MAIN )
119 continue;
120 if( $index === 0 )
121 $name = wfMsg( 'blanknamespace' );
122 $options[] = self::option( $name, $index, $index === $selected );
123 }
124
125 return Xml::openElement( 'select', array( 'id' => 'namespace', 'name' => $element_name,
126 'class' => 'namespaceselector' ) )
127 . "\n"
128 . implode( "\n", $options )
129 . "\n"
130 . Xml::closeElement( 'select' );
131 }
132
133 /**
134 * Create a date selector
135 *
136 * @param $selected Mixed: the month which should be selected, default ''
137 * @param $allmonths String: value of a special item denoting all month. Null to not include (default)
138 * @param string $id Element identifier
139 * @return String: Html string containing the month selector
140 */
141 public static function monthSelector( $selected = '', $allmonths = null, $id = 'month' ) {
142 global $wgLang;
143 $options = array();
144 if( is_null( $selected ) )
145 $selected = '';
146 if( !is_null( $allmonths ) )
147 $options[] = self::option( wfMsg( 'monthsall' ), $allmonths, $selected === $allmonths );
148 for( $i = 1; $i < 13; $i++ )
149 $options[] = self::option( $wgLang->getMonthName( $i ), $i, $selected === $i );
150 return self::openElement( 'select', array( 'id' => $id, 'name' => 'month', 'class' => 'mw-month-selector' ) )
151 . implode( "\n", $options )
152 . self::closeElement( 'select' );
153 }
154
155 /**
156 *
157 * @param $language The language code of the selected language
158 * @param $customisedOnly If true only languages which have some content are listed
159 * @return array of label and select
160 */
161 public static function languageSelector( $selected, $customisedOnly = true ) {
162 global $wgContLanguageCode;
163 /**
164 * Make sure the site language is in the list; a custom language code
165 * might not have a defined name...
166 */
167 $languages = Language::getLanguageNames( $customisedOnly );
168 if( !array_key_exists( $wgContLanguageCode, $languages ) ) {
169 $languages[$wgContLanguageCode] = $wgContLanguageCode;
170 }
171 ksort( $languages );
172
173 /**
174 * If a bogus value is set, default to the content language.
175 * Otherwise, no default is selected and the user ends up
176 * with an Afrikaans interface since it's first in the list.
177 */
178 $selected = isset( $languages[$selected] ) ? $selected : $wgContLanguageCode;
179 $options = "\n";
180 foreach( $languages as $code => $name ) {
181 $options .= Xml::option( "$code - $name", $code, ($code == $selected) ) . "\n";
182 }
183
184 return array(
185 Xml::label( wfMsg('yourlanguage'), 'wpUserLanguage' ),
186 Xml::tags( 'select',
187 array( 'id' => 'wpUserLanguage', 'name' => 'wpUserLanguage' ),
188 $options
189 )
190 );
191
192 }
193
194 public static function span( $text, $class, $attribs=array() ) {
195 return self::element( 'span', array( 'class' => $class ) + $attribs, $text );
196 }
197
198 public static function wrapClass( $text, $class, $tag='span', $attribs=array() ) {
199 return self::tags( $tag, array( 'class' => $class ) + $attribs, $text );
200 }
201
202 /**
203 * Convenience function to build an HTML text input field
204 * @return string HTML
205 */
206 public static function input( $name, $size=false, $value=false, $attribs=array() ) {
207 return self::element( 'input', array(
208 'name' => $name,
209 'size' => $size,
210 'value' => $value ) + $attribs );
211 }
212
213 /**
214 * Convenience function to build an HTML password input field
215 * @return string HTML
216 */
217 public static function password( $name, $size=false, $value=false, $attribs=array() ) {
218 return self::input( $name, $size, $value, array_merge($attribs, array('type' => 'password')));
219 }
220
221 /**
222 * Internal function for use in checkboxes and radio buttons and such.
223 * @return array
224 */
225 public static function attrib( $name, $present = true ) {
226 return $present ? array( $name => $name ) : array();
227 }
228
229 /**
230 * Convenience function to build an HTML checkbox
231 * @return string HTML
232 */
233 public static function check( $name, $checked=false, $attribs=array() ) {
234 return self::element( 'input', array_merge(
235 array(
236 'name' => $name,
237 'type' => 'checkbox',
238 'value' => 1 ),
239 self::attrib( 'checked', $checked ),
240 $attribs ) );
241 }
242
243 /**
244 * Convenience function to build an HTML radio button
245 * @return string HTML
246 */
247 public static function radio( $name, $value, $checked=false, $attribs=array() ) {
248 return self::element( 'input', array(
249 'name' => $name,
250 'type' => 'radio',
251 'value' => $value ) + self::attrib( 'checked', $checked ) + $attribs );
252 }
253
254 /**
255 * Convenience function to build an HTML form label
256 * @return string HTML
257 */
258 public static function label( $label, $id ) {
259 return self::element( 'label', array( 'for' => $id ), $label );
260 }
261
262 /**
263 * Convenience function to build an HTML text input field with a label
264 * @return string HTML
265 */
266 public static function inputLabel( $label, $name, $id, $size=false, $value=false, $attribs=array() ) {
267 return Xml::label( $label, $id ) .
268 '&nbsp;' .
269 self::input( $name, $size, $value, array( 'id' => $id ) + $attribs );
270 }
271
272 /**
273 * Convenience function to build an HTML checkbox with a label
274 * @return string HTML
275 */
276 public static function checkLabel( $label, $name, $id, $checked=false, $attribs=array() ) {
277 return self::check( $name, $checked, array( 'id' => $id ) + $attribs ) .
278 '&nbsp;' .
279 self::label( $label, $id );
280 }
281
282 /**
283 * Convenience function to build an HTML radio button with a label
284 * @return string HTML
285 */
286 public static function radioLabel( $label, $name, $value, $id, $checked=false, $attribs=array() ) {
287 return self::radio( $name, $value, $checked, array( 'id' => $id ) + $attribs ) .
288 '&nbsp;' .
289 self::label( $label, $id );
290 }
291
292 /**
293 * Convenience function to build an HTML submit button
294 * @param $value String: label text for the button
295 * @param $attribs Array: optional custom attributes
296 * @return string HTML
297 */
298 public static function submitButton( $value, $attribs=array() ) {
299 return self::element( 'input', array( 'type' => 'submit', 'value' => $value ) + $attribs );
300 }
301
302 /**
303 * Convenience function to build an HTML hidden form field.
304 * @todo Document $name parameter.
305 * @param $name FIXME
306 * @param $value String: label text for the button
307 * @param $attribs Array: optional custom attributes
308 * @return string HTML
309 */
310 public static function hidden( $name, $value, $attribs=array() ) {
311 return self::element( 'input', array(
312 'name' => $name,
313 'type' => 'hidden',
314 'value' => $value ) + $attribs );
315 }
316
317 /**
318 * Convenience function to build an HTML drop-down list item.
319 * @param $text String: text for this item
320 * @param $value String: form submission value; if empty, use text
321 * @param $selected boolean: if true, will be the default selected item
322 * @param $attribs array: optional additional HTML attributes
323 * @return string HTML
324 */
325 public static function option( $text, $value=null, $selected=false,
326 $attribs=array() ) {
327 if( !is_null( $value ) ) {
328 $attribs['value'] = $value;
329 }
330 if( $selected ) {
331 $attribs['selected'] = 'selected';
332 }
333 return self::element( 'option', $attribs, $text );
334 }
335
336 /**
337 * Build a drop-down box from a textual list.
338 *
339 * @param mixed $name Name and id for the drop-down
340 * @param mixed $class CSS classes for the drop-down
341 * @param mixed $other Text for the "Other reasons" option
342 * @param mixed $list Correctly formatted text to be used to generate the options
343 * @param mixed $selected Option which should be pre-selected
344 * @return string
345 */
346 public static function listDropDown( $name= '', $list = '', $other = '', $selected = '', $class = '', $tabindex = Null ) {
347 $options = '';
348 $optgroup = false;
349
350 $options = self::option( $other, 'other', $selected === 'other' );
351
352 foreach ( explode( "\n", $list ) as $option) {
353 $value = trim( $option );
354 if ( $value == '' ) {
355 continue;
356 } elseif ( substr( $value, 0, 1) == '*' && substr( $value, 1, 1) != '*' ) {
357 // A new group is starting ...
358 $value = trim( substr( $value, 1 ) );
359 if( $optgroup ) $options .= self::closeElement('optgroup');
360 $options .= self::openElement( 'optgroup', array( 'label' => $value ) );
361 $optgroup = true;
362 } elseif ( substr( $value, 0, 2) == '**' ) {
363 // groupmember
364 $value = trim( substr( $value, 2 ) );
365 $options .= self::option( $value, $value, $selected === $value );
366 } else {
367 // groupless reason list
368 if( $optgroup ) $options .= self::closeElement('optgroup');
369 $options .= self::option( $value, $value, $selected === $value );
370 $optgroup = false;
371 }
372 }
373 if( $optgroup ) $options .= self::closeElement('optgroup');
374
375 $attribs = array();
376 if( $name ) {
377 $attribs['id'] = $name;
378 $attribs['name'] = $name;
379 }
380 if( $class ) {
381 $attribs['class'] = $class;
382 }
383 if( $tabindex ) {
384 $attribs['tabindex'] = $tabindex;
385 }
386 return Xml::openElement( 'select', $attribs )
387 . "\n"
388 . $options
389 . "\n"
390 . Xml::closeElement( 'select' );
391 }
392
393 /**
394 * Returns an escaped string suitable for inclusion in a string literal
395 * for JavaScript source code.
396 * Illegal control characters are assumed not to be present.
397 *
398 * @param string $string
399 * @return string
400 */
401 public static function escapeJsString( $string ) {
402 // See ECMA 262 section 7.8.4 for string literal format
403 $pairs = array(
404 "\\" => "\\\\",
405 "\"" => "\\\"",
406 '\'' => '\\\'',
407 "\n" => "\\n",
408 "\r" => "\\r",
409
410 # To avoid closing the element or CDATA section
411 "<" => "\\x3c",
412 ">" => "\\x3e",
413
414 # To avoid any complaints about bad entity refs
415 "&" => "\\x26",
416
417 # Work around https://bugzilla.mozilla.org/show_bug.cgi?id=274152
418 # Encode certain Unicode formatting chars so affected
419 # versions of Gecko don't misinterpret our strings;
420 # this is a common problem with Farsi text.
421 "\xe2\x80\x8c" => "\\u200c", // ZERO WIDTH NON-JOINER
422 "\xe2\x80\x8d" => "\\u200d", // ZERO WIDTH JOINER
423 );
424 return strtr( $string, $pairs );
425 }
426
427 /**
428 * Encode a variable of unknown type to JavaScript.
429 * Arrays are converted to JS arrays, objects are converted to JS associative
430 * arrays (objects). So cast your PHP associative arrays to objects before
431 * passing them to here.
432 */
433 public static function encodeJsVar( $value ) {
434 if ( is_bool( $value ) ) {
435 $s = $value ? 'true' : 'false';
436 } elseif ( is_null( $value ) ) {
437 $s = 'null';
438 } elseif ( is_int( $value ) ) {
439 $s = $value;
440 } elseif ( is_array( $value ) ) {
441 $s = '[';
442 foreach ( $value as $elt ) {
443 if ( $s != '[' ) {
444 $s .= ', ';
445 }
446 $s .= self::encodeJsVar( $elt );
447 }
448 $s .= ']';
449 } elseif ( is_object( $value ) ) {
450 $s = '{';
451 foreach ( (array)$value as $name => $elt ) {
452 if ( $s != '{' ) {
453 $s .= ', ';
454 }
455 $s .= '"' . self::escapeJsString( $name ) . '": ' .
456 self::encodeJsVar( $elt );
457 }
458 $s .= '}';
459 } else {
460 $s = '"' . self::escapeJsString( $value ) . '"';
461 }
462 return $s;
463 }
464
465
466 /**
467 * Check if a string is well-formed XML.
468 * Must include the surrounding tag.
469 *
470 * @param $text String: string to test.
471 * @return bool
472 *
473 * @todo Error position reporting return
474 */
475 public static function isWellFormed( $text ) {
476 $parser = xml_parser_create( "UTF-8" );
477
478 # case folding violates XML standard, turn it off
479 xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
480
481 if( !xml_parse( $parser, $text, true ) ) {
482 //$err = xml_error_string( xml_get_error_code( $parser ) );
483 //$position = xml_get_current_byte_index( $parser );
484 //$fragment = $this->extractFragment( $html, $position );
485 //$this->mXmlError = "$err at byte $position:\n$fragment";
486 xml_parser_free( $parser );
487 return false;
488 }
489 xml_parser_free( $parser );
490 return true;
491 }
492
493 /**
494 * Check if a string is a well-formed XML fragment.
495 * Wraps fragment in an \<html\> bit and doctype, so it can be a fragment
496 * and can use HTML named entities.
497 *
498 * @param $text String:
499 * @return bool
500 */
501 public static function isWellFormedXmlFragment( $text ) {
502 $html =
503 Sanitizer::hackDocType() .
504 '<html>' .
505 $text .
506 '</html>';
507 return Xml::isWellFormed( $html );
508 }
509
510 /**
511 * Replace " > and < with their respective HTML entities ( &quot;,
512 * &gt;, &lt;)
513 *
514 * @param $in String: text that might contain HTML tags.
515 * @return string Escaped string
516 */
517 public static function escapeTagsOnly( $in ) {
518 return str_replace(
519 array( '"', '>', '<' ),
520 array( '&quot;', '&gt;', '&lt;' ),
521 $in );
522 }
523
524 /**
525 * Generate a form (without the opening form element).
526 * Output DOES include a submit button.
527 * @param array $fields Associative array, key is message corresponding to a description for the field (colon is in the message), value is appropriate input.
528 * @param string $submitLabel A message containing a label for the submit button.
529 * @return string HTML form.
530 */
531 public static function buildForm( $fields, $submitLabel ) {
532 $form = '';
533 $form .= "<table><tbody>";
534
535 foreach( $fields as $labelmsg => $input ) {
536 $id = "mw-$labelmsg";
537 $form .= Xml::openElement( 'tr', array( 'id' => $id ) );
538
539 $form .= Xml::element( 'td', array('valign' => 'top'), wfMsg( $labelmsg ) );
540
541 $form .= Xml::openElement( 'td' ) . $input . Xml::closeElement( 'td' );
542
543 $form .= Xml::closeElement( 'tr' );
544 }
545
546 $form .= "</tbody></table>";
547
548 $form .= Xml::submitButton( wfMsg($submitLabel) );
549
550 return $form;
551 }
552 }